I have an iOS app that needs to process a response from a web service. The response is a serialized JSON string containing a serialized JSON object, looking something like this:
"{ \"name\" : \"Bob\", \"age\" : 21 }"
Note that this response is a JSON string, not a JSON object. What I need to do is deserialize the string, so that I get this:
{ "name" : "Bob", "age" : 21 }
And then I can use +[NSJSONSerialization JSONObjectWithData:options:error:]
to deserialize that into an NSDictionary
.
But, how do I do that first step? That is, how to I "unescape" the string so that I have a serialized JSON object? +[NSJSONSerialization JSONObjectWithData:options:error:]
only works if the top-level object is an array or a dictionary; it doesn't work on strings.
I ended up writing my own JSON string parser, which I hope conforms to section 2.5 of RFC 4627. But I suspect I've overlooked some easy way to do this using NSJSONSerialization
or some other available method.
If you have nested JSON, then just call JSONObjectWithData
twice:
NSString *string = @"\"{ \\\"name\\\" : \\\"Bob\\\", \\\"age\\\" : 21 }\"";
// --> the string
// "{ \"name\" : \"Bob\", \"age\" : 21 }"
NSError *error;
NSString *outerJson = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingAllowFragments error:&error];
// --> the string
// { "name" : "Bob", "age" : 21 }
NSDictionary *innerJson = [NSJSONSerialization JSONObjectWithData:[outerJson dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
// --> the dictionary
// { age = 21; name = Bob; }