从表单的套接字数据中读取字典的正确方法是什么:
{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}
请注意,有独立的json词典,我们需要将其转换为词典列表。我们总是可以使用stringByReplacingOccurrencesOfString方法替换“} {”。但是有更好的方法吗?
答案 0 :(得分:3)
假设您已将字符串字典放入字典中:
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,而不是应用无聊和自定义解析。
答案 1 :(得分:-1)
var dictionary = ["key" : "value", "key1" : "value1", "key2" : "value2", "Key3" : "Value3"]
for (key, value) in companies
{
println("\(value)")
}