测试后,我只能让 [NSJSONSerialization isValidJSONObject:]
对我已经使用 [NSJSONSerialization JSONObjectWithData:options:error:] 解析的 JSON 数据返回肯定值
.
isValidJSONObject returns a Boolean value that indicates whether a given object can be converted to JSON data.
然而,尽管我尝试从 JSON 转换为 NSDictionary 的对象转换得很好,isValidJSONObject
返回 NO
。
这是我的代码:
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);
我的日志包含以下内容:
data is not JSON
dict is JSON
然后是dict的输出,此时它是一个巨大的NSMutableDictionary对象。运行此代码时不会生成任何错误,但在 data
上运行时,isValidJSONObject
似乎返回错误的值。
如何让 isValidJSONObject
按预期工作?
最佳答案
isValidJSONObject
测试 JSON 对象(NSDictionary
或 NSArray
)是否可以成功
转换为 JSON 数据。
它不是用于测试 NSData
对象是否包含有效的 JSON 数据。测试是否有效
您刚刚调用的 JSON 数据
[NSJSONSerialization JSONObjectWithData:data ...]
并检查返回值是否为nil
。
关于objective-c - isValidJSONObject 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49262122/