objective-c - isValidJSONObject 未按预期工作

标签 objective-c json cocoa-touch

测试后,我只能让 [NSJSONSerialization isValidJSONObject:] 对我已经使用 [NSJSONSerialization JSONObjectWithData:options:error:] 解析的 JSON 数据返回肯定值.

根据official documentation :

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 对象(NSDictionaryNSArray)是否可以成功 转换为 JSON 数据

它不是用于测试 NSData 对象是否包含有效的 JSON 数据。测试是否有效 您刚刚调用的 JSON 数据

[NSJSONSerialization JSONObjectWithData:data ...]

并检查返回值是否为nil

关于objective-c - isValidJSONObject 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49262122/

相关文章:

php - golang,revel,如何解析 post json?

javascript - 如何使用 Ajax 调用在 MVC 中的返回 View 方法中返回 JSON 数据

iphone - 如何清除字典?

ios - 当从另一个类调用方法时歌曲不播放

objective-c - 休息套件 "*** Assertion failure in -[RKManagedObjectMapping initWithEntity:]"

objective-c - 检查 Objective C 中的资源分支

javascript - 为什么在 javascript 中的 JSON 对象数组中创建一个额外的数组数组

objective-c - 在 Cocoa 应用程序上接受拖动的文件

ios - 在 Storyboard 中以编程方式创建的 UITableView 的自定义 tableview 单元格

ios - 你能以编程方式接受 UITextView 中的拼写更正吗?