Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 401
Bot Avatar asked Mar 29 '12 22:03

Bot


1 Answers

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.

like image 172
hypercrypt Avatar answered Sep 29 '22 05:09

hypercrypt