Xcode 8.1 部署目标 iOS 9.0
我从中的 Foursquare Venue Search 端点得到了一系列紧凑的 field 对象......
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
当我使用...检查数据对象时
if ([NSJSONSerialization isValidJSONObject:data])
我猜错了。
谁能告诉我这里出了什么问题?
编辑: 这是完整的 if block (在将类型转换添加到 if block 中的 data 之后)...
id foundationObject;
NSLog(@"data:- %@",data);
if ([NSJSONSerialization isValidJSONObject:(id)data])
{
foundationObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"venues foundation object:- %@",foundationObject);
}
之前的代码没有 if block 。只是……
id foundationObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
当我意识到(在上述语句之后使用断点)foundationObject 为 nil 而 data 不是时,我做出了更改。
注意:我在 3 月份为 iOS 9.x 发布我的应用程序时,它运行良好。被调用的 Venue Endpoint 的版本会有所不同吗?
最佳答案
您在这里测试的是 NSData。 isValidJSONObject
的输入是 id
而不是 NSData
+ (BOOL)isValidJSONObject:(id)obj;
如果obj可以转换为JSON数据(NSData
),则返回YES
,否则返回NO。
此外,根据文档,
An object that may be converted to JSON must have the following properties:
- The top level object is an NSArray or NSDictionary.
- All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
- All dictionary keys are instances of NSString.
- Numbers are not NaN or infinity.
Calling isValidJSONObject: or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.
要将NSData
转换成JSONObject,可以使用下面的代码
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (!error) {
// successfully done.
}else {
NSLog(@"error: %@", error.localizedDescription)
}
请注意,要找出您从服务器接收到的 jsonData(NSData
) 有什么问题,您必须将 NSError
对象传递到方法中,如下所示上面的代码。如果NSData
转换成jsonObject失败,可以根据它查找原因。
请看这个link有关在 Objective-C 中使用 NSError
对象的更多信息
关于ios - NSJSONSerialization isValidJSONObject 为从 Venue 搜索端点接收到的数据返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40635993/