Check if the API response is correct. Json

Is there a way to NSJSONSerialization

check what NSData

is valid JSON? I don't want the app to be rejected 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];



source to share

3 answers

It won't be an "error", it will just return zero if the JSON is invalid. So the test to check if the JSON is valid would be:

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


If it returns nil

, you can check error

to see what went wrong.




The class has a way to do exactly that ... ( 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 hypercripts comment)

Hypercrypt is right (I really don't understand how I missed this) ... While my answer seems to work, it is wrong . The method isValidJSONObject:

does this to check if the object can be serialized to JSON and not vice versa. Therefore, his answer is what you are looking for. You can use this method in case you grab the modified copy from the json payload, modify it, and then want to check if you can try and re-serialize it back to a JSON string. But the bottom line is that the hypercript's answer is correct, and I think it would be fairer to mark his answer as correct rather than mine. Anyway, sorry for any confusion and thanks to @hypercrypt for pointing out that :)



There is really no way to validate data without creating an object using NSJSONSerialization; I would put it in a try. If you get caught in a catch block, this is not valid JSON.

EDIT: Think about it if it encounters an error, "error" is an error object. Therefore, even if nothing is thrown away, you can check this to make sure the data is valid.



All Articles