【发布时间】:2014-01-18 19:20:23
【问题描述】:
当我的应用同时接收多个 JSON 对象时,我遇到了一些麻烦。我正在使用一个对我的服务器开放的 TCP 套接字,它向我发送消息。我似乎收到多条消息的原因可能是由于网络滞后。
这是服务器消息的样子(然后我将其放入 NSString 并尝试解析 JSON):
{
"id": "156806",
"type": "message",
"userCity": "",
"userCountry": "",
"os": "",
"browser": "",
"trafficType": "",
"seKeyword": "",
"seType": "",
"currentPage": "",
"userId": "1",
"agentId": "352",
"customField1": "",
"visitorNick": "Visitor 147220060",
"msg": "asd",
"time": "16:05",
"channel": "V147220060",
"visits": "254"
} {
"type": "previewStopped",
"msg": "",
"visitorNick": "Mackan",
"customField1": "",
"visitorNick": "Visitor V147220060",
"time": "16:05",
"channel": "V147220060"
} {
"id": "156807",
"type": "message",
"userCity": "",
"userCountry": "",
"os": "",
"browser": "",
"trafficType": "",
"seKeyword": "",
"seType": "",
"currentPage": "",
"userId": "1",
"agentId": "352",
"customField1": "",
"visitorNick": "Visitor 147220060",
"msg": "as",
"time": "16:05",
"channel": "V147220060",
"visits": "254"
} {
"id": "156808",
"type": "message",
"userCity": "",
"userCountry": "",
"os": "",
"browser": "",
"trafficType": "",
"seKeyword": "",
"seType": "",
"currentPage": "",
"userId": "1",
"agentId": "352",
"customField1": "",
"visitorNick": "Visitor 147220060",
"msg": "da",
"time": "16:05",
"channel": "V147220060",
"visits": "254"
}
这是我目前解析 NSString 的方式,请注意上面的 JSON 在下面的代码中是 outputData:
// Parse the message from the server
NSError* error;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [outputData dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
NSString* type = [JSON objectForKey:@"type"];
if(error) {
NSLog(@"PARSE ERROR ------------->>>>> : %@\n", error);
}
NSLog(@"SERVER TYPE --> %@\n", type);
if([type isEqualToString:@"message"]) {
[self messageReceived:outputData];
}
当我在outputData 中只收到一个 JSON 时,上述方法非常有效,但是当收到多个 JSON 时,它会引发错误:
解析错误 ------------->>>>> : 错误域=NSCocoaErrorDomain Code=3840 “操作无法完成。(Cocoa 错误 3840。)” (最后的垃圾。) UserInfo=0x14e9acb0 {NSDebugDescription=垃圾在 结束。}
任何想法如何处理这个?
【问题讨论】:
-
可以添加
[outputData dataUsingEncoding:NSUTF8StringEncoding]的输出吗? -
在一个包中获取多个 JSON 实体是不寻常的。通常,服务器将其包装成一个 JSON 数组,其中多个实体是数组中的一项。你能让服务器把你的 JSON 实体包装成一个单一的 JSON 结构吗?如果做不到这一点,您将不得不自己解析 JSON 并一次将它们提供给解析器。
-
@yoeriboven 不确定我是否关注,您希望我向控制台回显什么变量?
-
尝试将
NSJSONReadingMutableContainers更改为NSJSONReadingAllowFragments -
您的服务器返回错误信息,您发布的不是有效的json,应以逗号分隔并包裹在数组括号中 [{"id":1}, {"id":2 }]。您还希望将结果分配给 NSAray,而不是 NSDictionary。验证您的 json 与 jsonlint.com
标签: ios objective-c