NSJSONSerialization returns zero

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

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

[NSJSONSerialization isValidJSONObject:data]

says this is not a valid JSON object.

Can someone point out the mistake I made, or think about the reason why this is happening?

+5
source share
1 answer

I am sure that your line has a non-printable character, which makes the data invalid.

Declare a variable NSError* error, then call the method [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]to try to convert JSON: obviously, if your data is considered invalid, it will return nil, but at least you will have a description of what is wrong in NSError* errorafter 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
+9

All Articles