NSJSONSerialization
有没有办法检查 NSData
是有效的 JSON?如果 API 出于某种原因返回无效的 JSON,我不希望应用程序出错。
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
最佳答案
这不会“出错”,如果 JSON 无效,它只会返回 nil。因此,查看它是否是有效 JSON 的测试将是:
NSError *error;
if ([NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error] == nil)
{
// Handle error
}
如果它确实返回了 nil
那么您可以检查 error
看看哪里出了问题。
关于objective-c - 检查来自 API 的响应是否为有效的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9934210/