nsjsonserializationjsonkit

JSONKit not deserializing property without quotes


I'm trying to deserilaize the following into an NSDictionary using both JSONKit and Apple's built in json serlializer

{route:"/tasks/4f9218a27e5c8f0000000000"}

why does it fail

NSDictionary *jsonDictionary = [[JSON valueForKeyPath:@"data"] objectFromJSONString];

It does however seem to work if I have quotes around "route", why? I would just put quotes around the property name but facebook strips it out when I post the original string so that's not a possibility.


Solution

  • The reason is because {"key":"value"} is the proper way to encode a JSON string. the { key: "value" } encoded strings that you see in applications is typically a convenience factor of defining the string as, before this sort of structured string is pushed via HTTP, it is translated (behind the scenes) to the {"key":"value"} format.

    In the future, if you are having issues with a JSON string and are worried it may because of improper JSON string formatting, try pasting the JSON string into JSONlint (http://jsonlint.com/).

    If you go there and try this string, you'll see it fail: { key: "value" } If you try this one instead, it will pass: { "key": "value" }

    Hope this helps....

    EDIT Wow... Guess it would have helped if I actually read what I was writing. The point is there above, but I must have had a brain fart as it is kind of hard to decipher. So, here is the second attempt at this hah..

    The reason your first example fails is because this its structure is not valid per JSON standards:

    {route:"/tasks/4f9218a27e5c8f0000000000"}  // This is invalid...
    

    A proper key/value pair that is valid has both the key and value surrounded by double quotes:

    { "route" : "/tasks/4f9218a27e5c8f0000000000" }  // This IS valid.
    

    The standards for defining JSON strings can be seen here: http://www.json.org/

    The JSONLint site (http://jsonlint.com) is a very good resource for quickly testing the validity of your JSON string prior to using it in the real world, and also a great way to debug a JSON string that may be failing the parser validation test.

    I hope this helps heh..