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.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
I have found that the easiest and best way to remove all escape characters from your JSON string, is to pass the string into Regex. Unescape() method. This method returns a new string with no ecapes, even \n \t etc, are removed.
JSON is pretty liberal: The only characters you must escape are \ , " , and control codes (anything less than U+0020). This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit¹ for that character.
If you have to use special character in your JSON string, you can escape it using \ character. See this list of special character used in JSON : \b Backspace (ascii code 08) \f Form feed (ascii code 0C) \n New line \r Carriage return \t Tab \" Double quote \\ Backslash character.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With