JSON 中的无效类型写入 (RTCIceCandidate)

Invalid type in JSON write (RTCIceCandidate)

我正在使用 websocket 来调用 received、accept 等等。我在接受呼叫时收到 websocket 事件。

websocket 接受事件输出:-

{
    action = signal;
    "call_id" = 60a4d5b4850b3875f95dbc6e;
    event = CALL;
    from = 5b30ec0fa4cef4609038470b;
    id = "330A1A48-A6BA-4B29-A4A2-9D9FDB85144D";
    signal =     {
        offer = "RTC_OBJC_TYPE(RTCIceCandidate):\naudio\n0\ncandidate:1211696075 1 udp 41885439 3.8.66.208 62545 typ relay raddr 0.0.0.0 rport 0 generation 0 ufrag DT/j network-id 1 network-cost 10\nturn:3.8.66.208:3478?transport=udp";
    };
    to = 5b4854724f82e91934c1c475;
}

我正在使用下面的代码将上面的字典对象转换为 json 字符串。

-(NSString *)convertDictionaryToJsonString:(NSMutableDictionary *)dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

问题:- 应用程序崩溃,原因是 - 'Invalid type in JSON write (RTCIceCandidate)'

谁能知道如何避免崩溃并解决这个问题?

谢谢。

以下是 JSON 的有效类型:

A Foundation object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.

你的错误是说在某些时候,有一个对象不是允许的类型,它是 RTCIceCandidate

看到 "RTC_OBJC_TYPE(RTCIceCandidate):\naudio\n0\ncandidate:1211696075 1 udp 41885439 3.8.66.208 62545 typ relay raddr 0.0.0.0 rport 0 generation 0 ufrag DT/j network-id 1 network-cost 10\nturn:3.8.66.208:3478?transport=udp" 让你认为它确实是一个 NSString 但是,如果我们看到 RTCIceCandidate 的代码(因为它是罪魁祸首 class),我们就会看到覆盖 description:

- (NSString *)description {
  return [NSString stringWithFormat:@"RTCIceCandidate:\n%@\n%d\n%@\n%@",
                                    _sdpMid,
                                    _sdpMLineIndex,
                                    _sdp,
                                    _serverUrl];
}

有一个 RTCIceCandidate+JSON extension 提供了一些有趣的方法将 RTCIceCandidate 转换为 JSONString/JSONData。

您需要将罪魁祸首对象替换为允许的对象 class。

RTCIceCandidate *candidate = dict["signal"]["offer"];
NSString/NSDictionary *candidateValid = //Whatever the method you want with a method from RTCIceCandidate+JSON, custom one ?

dict[@"signal"] = @{@"offer": candidateValid}; //Because I guess that dict[@"signal"] is in a fact a `NSDictionary` and not a `NSMutableDictionary`

//Current code