1

In the following code for parsing a JSON, when objects happen to be other than NSArray or NSDictionary, NSJSONReadingAllowFragments is used.

The below code works fine and prints out 32. but if replace 32 by abcd, it outputs to null. Any idea why its null for a string abcd.

NSString *num=@"32";
NSError *error;
NSData *createdData = [num dataUsingEncoding:NSUTF8StringEncoding];
id response=[NSJSONSerialization JSONObjectWithData:createdData options:NSJSONReadingAllowFragments error:&error];
NSLog(@"Response= %@",response);
2
  • 3
    Remark: If a method fails and you don't know why, and that method has an error parameter - why don't you use that parameter to get information about the problem?
    – Martin R
    Jun 6, 2013 at 11:43
  • Thanks Martin, i will add that too.
    – weber67
    Jun 6, 2013 at 11:44

1 Answer 1

3

That’s because 32 is a valid JSON fragment (a number), but abcd is not a valid JSON fragment since all strings must be quoted. Try:

NSString *num=@"\"abcd\"";

which produces "abcd" instead of abcd.

(also, bear in mind that the object being returned is not really an NSDictionary, so declaring it as id makes more sense)

6
  • 1
    That was a nice answer, waiting for 3 minutes to pass by so I can tick the answer.
    – weber67
    Jun 6, 2013 at 11:44
  • It does not matter how you declare the variable, so NSDictionary *responseDictionary is OK if you expect a dictionary. But verifying that with isKindOfClass: would make sense.
    – Martin R
    Jun 6, 2013 at 11:47
  • Yes I will add that too. The response that I will get is NSDictionary, but adding a check will save me from a exception if some how it comes out to be other than NSDictionary
    – weber67
    Jun 6, 2013 at 11:49
  • @MartinR It does work at both compile- and run-time, but using id and then casting to the correct type after judicious use of -isKindOfClass: makes the code clearer, also allowing static typing and analysis.
    – user557219
    Jun 6, 2013 at 11:50
  • @Bavarious I see I have a complex JSON, and using the following code makes things more complex to understand ex: id allFriends=[response objectForKey:@"friends"]; if([allFriends isKindOfClass:[NSDictionary class]]){ NSDictionary allFriendsDictionary=(NSDictionary) allFriends; } . Here allFriends and allFriendsDictionary is quite confusing, so any suggestions on it. There are many dictionary and array in the response.
    – weber67
    Jun 6, 2013 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.