IsValidJSONObject does not work as expected

After testing, I can get [NSJSONSerialization isValidJSONObject:] to return positive JSON data that I have already analyzed using [NSJSONSerialization JSONObjectWithData:options:error:] .

According to official documentation:

isValidJSONObject returns a boolean value indicating whether the given object can be converted to JSON data.

However, despite the fact that the objects I'm trying to convert from JSON to 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 journal contains the following:

 data is not JSON dict is JSON 

and then the output of the dict, which at this moment is a huge NSMutableDictionary object. When this code is run, no errors are generated, but isValidJSONObject seems to return the wrong value when run on data .

How can I get isValidJSONObject to work as expected?

+8
json objective-c cocoa-touch
source share
1 answer

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

This is not for testing if the NSData object contains valid JSON data. To validate JSON data that you only call

 [NSJSONSerialization JSONObjectWithData:data ...] 

and check if the return value is nil or not.

+23
source share

All Articles