Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSJSONSerialization returning nil

{"User":{"id":"42","name":"martin"}}

Converting my NSData to NSString returns this JSON which seems completely valid, however the method:

[NSJSONSerialization isValidJSONObject:data]

is saying this is not a valid JSON object.

Could anyone point out a mistake I have made or think of a reason why this is happening?

like image 359
Alex Avatar asked Apr 16 '13 18:04

Alex


1 Answers

I bet there is a non-printable character in your string for example, making the data invalid.

Declare an NSError* error variable then call [NSJSONSerialization JSONObjectWithData:data options:0 error:&error] method to try to convert the JSON: obviously if your data is considered invalid, it will return nil, but at least you will have the description of what's wrong in the NSError* error variable after that.

NSData* data = ... // your data
NSError* error = nil; // Declare a variable to hold the error upon return
id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // Try to convert your data
NSLog(@"obj: %@ ; error: %@", error); // Log the decoded object, and the error if any
like image 88
AliSoftware Avatar answered Sep 28 '22 02:09

AliSoftware