isValidJSONObject无法按预期工作

Jim*_*ery 8 cocoa-touch json objective-c

经过测试,我只能[NSJSONSerialization isValidJSONObject:]对已经解析过的JSON数据返回正数[NSJSONSerialization JSONObjectWithData:options:error:].

根据官方文件:

isValidJSONObject返回一个布尔值,指示是否可以将给定对象转换为JSON数据.

但是,尽管我试图从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);
Run Code Online (Sandbox Code Playgroud)

我的日志包含以下内容:

data is not JSON
dict is JSON
Run Code Online (Sandbox Code Playgroud)

然后是dict的输出,在这一点上是一个巨大的NSMutableDictionary对象.运行此代码时不会生成错误,但在运行时isValidJSONObject似乎返回了错误的值data.

我怎样才能isValidJSONObject按预期工作?

Mar*_*n R 25

isValidJSONObject测试JSON对象(a NSDictionaryNSArray)是否可以成功转换为JSON数据.

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

[NSJSONSerialization JSONObjectWithData:data ...]
Run Code Online (Sandbox Code Playgroud)

并检查返回值是否为nil.

  • 我试过这个,但是如果数据不是有效的json,JSONObjectWithData会崩溃. (3认同)
  • @LuisEspinoza:根据我的经验,如果数据是无效的JSON,JSONObjectWithData返回nil(并设置error参数). (2认同)