Cocoa - Parse a JSON string
-
13-12-2019 - |
Question
I know that the web is full of examples about this, but I've tried everything, and I'm missing something. I want to parse a JSON string into a dicionary.
E have this response of the server:
{"type":"response", "action":"mkac", "result":"[{"Band":"Adele","Hits":422},{"Band":"Bryan Adams","Hits":93},{"Band":"Adai","Hits":30},{"Band":"Adamo","Hits":18},{"Band":"Adelle","Hits":15}]"}
And I make:
NSError *parseError = nil;
NSDictionary *outputDictionary =
[NSJSONSerialization JSONObjectWithData: [output dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &parseError];
NSLog(@"server said: %@", [outputDictionary objectForKey:@"result"]);
But the outputDictionary allways gives me null.
Can anyone help me with that?
Thanks a lot.
Solution
Yes, your json is malformed. If you format it properly, you'll see why:
{
"type":"response",
"action":"mkac",
"result":"[{"Band":"Adele","Hits":422},{"Band":"Bryan Adams","Hits":93},{"Band":"Adai","Hits":30},{"Band":"Adamo","Hits":18},{"Band":"Adelle","Hits":15}]"
}
You'll notice that the value for "result"
starts with a "
character, which means that the value is technically "[{"
. However after that, it comes across Band
. Since Band
isn't surrounded in double quotes (or preceded by a ,
or a }
, etc), it generates a parse error. If you remove the double quote immediately before [{
and immediately after }]
, then it parses correctly:
{
"type":"response",
"action":"mkac",
"result":[
{
"Band":"Adele",
"Hits":422
},
{
"Band":"Bryan Adams",
"Hits":93
},
{
"Band":"Adai",
"Hits":30
},
{
"Band":"Adamo",
"Hits":18
},
{
"Band":"Adelle",
"Hits":15
}
]
}
OTHER TIPS
I figured out what happened. The json string was no valid, because of "[ that I had to replace with just [