Question

Is there a way with NSJSONSerialization to check that the NSData is valid JSON? I don't want the application to error out if the API returns invalid JSON for some reason.

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Was it helpful?

Solution

This won't "error out", it'll just return nil if the JSON isn't valid. Thus the test to see if it is valid JSON would be:

NSError *error;
if ([NSJSONSerialization JSONObjectWithData:data
                                    options:kNilOptions
                                      error:&error] == nil)
{
    // Handle error
}

If it does return nil then you can check error to see what went wrong.

OTHER TIPS

NSJSONSerialization Class have a method to do exactly this... (EDIT: no it doesn't...)

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
id jsonObj = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
BOOL isValid = [NSJSONSerialization isValidJSONObject:jsonObj];

EDIT: (After hypercrypts' comment)

Hypercrypt is right (I really can't understand how I missed that)... Even though my answer seems to be working, it's wrong. What isValidJSONObject: method does is to check if an object can be serialized into JSON and not the other way round. So his answer is what you're looking for. You could use though this method in the case you grab a mutable copy from a json payload, mutate it and later want to check if it's safe to try and re-serialize it back to a JSON string. But bottom line is that hypercrypt's answer is the correct one and I think that it would be more than fair to mark his answer as correct instead of mine. Anyway, sorry about any confusion and @hypercrypt thank's for pointing that out :)

There isn't really a way to check the data without creating the object with NSJSONSerialization; I would put it in a try-catch. If you end up in the catch block, it's not valid JSON.

EDIT: Come to think of it, if it encountered an error, 'error' is an error object. So even if nothing is thrown you can check that to see if the data was valid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top