从以下形式的套接字数据读取字典的正确方法是什么:
{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}
注意有独立的 json 字典,我们需要将其转换为字典列表。我们始终可以使用 stringByReplacingOccurrencesOfString 方法通过替换“}{”来做到这一点。但有更好的方法吗?
最佳答案
假设您已经将 string-dictionary 放入字典中:
NSDictionary* jsonSocketData;
for(NSDictionary* data in jsonSocketData[@"data"]) {
/* whatever */
NSLog(@"%@", data[@"abc"]);
}
顺便说一句,我希望您的请求的结果更像是这样:
{
"result": [
{
"data": {
"abc": [],
"pqr": []
},
"error": ""
},
{
"data": {
"abc": [],
"pqr": []
},
"error": ""
}
]
}
如果您必须将 NSString (json) 转换为 NSDictionary:
NSString* jsonString = @"..";
NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
编辑
如果您发布的字符串与您收到的字符串完全相同,我会使用此技巧(这样 json 将格式良好):
NSString* response = @"...";
/* only if you are sure about format */
response = [response stringByReplacingOccurrencesOfString: @"}{" withString:@"},{"];
/* otherwise you can apply regex, defintely more flexible, with pattern "}(.?){" */
response = [NSString stringWithFormat:@"{\"result\":[%@]}", response];
完成此技巧后,您可以应用上面的代码。 顺便说一句,在我看来,最好的方法是拥有格式良好的 json,而不是应用无聊的自定义解析。
关于ios - 如何从套接字连接读取字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29749596/