iOS JSON Parse not working (returns null dictionary)

ios, json, nsjsonserialization, parsing

Solution

Probably you have some unprintable character that you cannot see. Try this:

NSData *jsonData = ...
const unsigned char *ptr = [data bytes];

for(int i=0; i<[data length]; ++i) {
  unsigned char c = *ptr++;
  NSLog(@"char=%c hex=%x", c, c);
}

To verify you don't have unprintable characters at the beginning or end of the data.

EDIT: to clarify, just run the above on your JSON dictionary - the one that fails to parse.

Problem

I use the `NSJSONSerialization`'s `JSONObjectWithData:data options: error:` to parse JSON data returned from a server. Now for the options parameter I use: `NSJSONReadingAllowFragments`. You can look below and see the actual JSON (where I believe the problem is). The error message I get is: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x6895da0 {NSDebugDescription=Invalid value around character 0.} Any idea how to fix it? JSON = ``` {"name":"Johan Appleseed", "email":"j.appleseed@emuze.co", "phone":"+4121876003", "accounts":{ "facebook":[true,1125], "twitter":[false,null], "homepage":[true,"http:\/\/johnAplleseed.com\/index.html"]}} ```

Original source

Related problems