Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
565 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...