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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…