Ios – Check if response from API is valid JSON


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

Best 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
                                      error:&error] == nil)
    // Handle error

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