Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

objective c - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...