isValidJSONObject不能按预期工作 [英] isValidJSONObject not working as expected
问题描述
测试后,我只能得到 [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不是JSON);
}
NSLog(@%@,dict);
我的日志包含以下内容:
数据不是JSON
dict是JSON
然后是dict的输出,这在这一点上是一个巨大的NSMutableDictionary对象。运行此代码时不会生成错误,但 isValidJSONObject
似乎在 data
上运行时返回错误的值。 / p>
如何获得 isValidJSONObject
以按预期工作?
isValidJSONObject
测试一个 JSON对象( NSDictionary
或 NSArray
)可以成功
转换为 JSON数据
不是用于测试 NSData
对象是否包含有效的 JSON数据。要测试有效的
JSON数据,您只需调用
[NSJSONSerialization JSONObjectWithData:data ...]
并检查返回值是否 nil
/ p>
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?
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.
这篇关于isValidJSONObject不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!