Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isValidJSONObject not working as expected

After testing, I can only get [NSJSONSerialization isValidJSONObject:] to return a positive on JSON data that I have already parsed with [NSJSONSerialization JSONObjectWithData:options:error:].

According to the official documentation:

isValidJSONObject returns a Boolean value that indicates whether a given object can be converted to JSON data.

However, despite the fact that the objects I am attempting to convert from JSON to a NSDictionary convert fine, isValidJSONObject returns NO.

Here is my code:

NSURL * url=[NSURL URLWithString:urlString];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error=[[NSError alloc] init];
NSMutableDictionary * dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

if([NSJSONSerialization isValidJSONObject:data]){
    NSLog(@"data is JSON");
}else{
    NSLog(@"data is not JSON");
}

if([NSJSONSerialization isValidJSONObject:dict]){
    NSLog(@"dict is JSON");
}else{
    NSLog(@"dict is not JSON");
}

NSLog(@"%@",dict);

My log contains the following:

data is not JSON
dict is JSON

and then the output of dict, which at this point is a huge NSMutableDictionary object. No errors are generated when running this code, but isValidJSONObject seems to be returning the wrong value when run on data.

How can I get isValidJSONObject to work as expected?

like image 470
Jimmery Avatar asked Jun 17 '13 14:06

Jimmery


1 Answers

isValidJSONObject tests if a JSON object (a NSDictionary or NSArray) can be successfully converted to JSON data.

It is not for testing if an NSData object contains valid JSON data. To test for valid JSON data you just call

[NSJSONSerialization JSONObjectWithData:data ...]

and check if the return value is nil or not.

like image 66
Martin R Avatar answered Nov 12 '22 08:11

Martin R