Check if response from API is valid JSON

Bot picture Bot · Mar 30, 2012 · Viewed 11.6k times · Source

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];

Answer

hypercrypt picture hypercrypt · Mar 30, 2012

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.