Reputation: 1863
Whats the right way to read the dictionaries from socket data of the form:
{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}{"data": {"abc": [], "pqr": []}, "error": ""}
Notice there are independent json dictionaries and we need to convert that into list of dictionaries. We can always do so using stringByReplacingOccurrencesOfString method by replacing "}{". But is there a better approach?
Upvotes: 2
Views: 158
Reputation: 21528
Suppose that you already put string-dictionary in a dictionary:
NSDictionary* jsonSocketData;
for(NSDictionary* data in jsonSocketData[@"data"]) {
/* whatever */
NSLog(@"%@", data[@"abc"]);
}
By the way I hope result of your request is more like this:
{
"result": [
{
"data": {
"abc": [],
"pqr": []
},
"error": ""
},
{
"data": {
"abc": [],
"pqr": []
},
"error": ""
}
]
}
If you have to convert your NSString (json) to NSDictionary:
NSString* jsonString = @"..";
NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
If string you posted is the exact string that you receive I would this trick (in this way the json will be well-formed):
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];
After this trick, you can apply code above. Btw, in my opinion, best way is to have a well-formed json rather than apply boring and custom parsing.
Upvotes: 3
Reputation: 1415
var dictionary = ["key" : "value", "key1" : "value1", "key2" : "value2", "Key3" : "Value3"]
for (key, value) in companies
{
println("\(value)")
}
Upvotes: -1