OGeek|极客世界-中国程序员成长平台

标题: iphone - 无法在 Objective-C 中访问 JSON 数据 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 03:04
标题: iphone - 无法在 Objective-C 中访问 JSON 数据

好的,这是我在 Objective-C 中使用 JSON 的第一种方法(我对最后一种方法也很陌生)。我要获取存储在我的 json 中的信息以在 Objective-C 中使用它们,但是当尝试加载它时,我得到 null 以响应 NSLog(@"%@",allData); on。谁能告诉我我做错了什么?提前感谢您的时间和耐心。 哦,如果需要,这里是 json: http://jsonviewer.stack.hu/#http://conqui.it/ricette.json

NSString *filePath = [[NSBundle mainBundle] pathForResource"recipes" ofType"json"];

NSError *error = nil;

NSMutableData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
NSLog(@"%@",JSONData);


NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
NSLog(@"%@",allData);

for (NSDictionary *diction in allData) {
    NSString *recipe = [diction objectForKey"recipe"];

    [array addObject:recipe];
}

NSLog(@"%@",array);



Best Answer-推荐答案


JSONObjectWithData 方法有一个 error 参数,您可以利用该参数来诊断问题。例如:

NSError *error = nil;
NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData
                                                   options:0
                                                     error:&error];
if (error)
    NSLog(@"%s: JSONObjectWithData error: %@", __FUNCTION__, error);

在您的评论中,您建议您收到有关“字符 414 周围未转义的控制字符”的错误。这表明 JSON 本身存在错误,您可能希望通过将其复制到 http://jsonlint.com/ 中来进行验证。看看它是否报告了任何问题。

针对是否存在任何 Objective-C 问题的更广泛的问题,本身没有编码错误。我无法评论 for循环,它清楚地假设 allData 是一个字典数组,如果没有看到 JSON,我就无法证明它。但我会相信你的话。但是,是的,Objective-C 代码看起来不错(尽管对返回值类型和错误对象的检查有点轻率)。

例如,如果您想要一些可以在开发期间使用的诊断断言语句,您可以执行以下操作:

NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
NSAssert(error, @"%s: JSONObjectWithData error: %@", __FUNCTION__, error);

NSLog(@"%s: array=%@", __FUNCTION__, array);

NSAssert([allData isKindOfClass:[NSArray class]], @"allData is not an array");

for (NSDictionary *diction in allData) {
    NSAssert([diction isKindOfClass:[NSDictionary class]], @"%s: diction is not a dictionary (%@), __FUNCTION__, diction);

    NSString *recipe = [diction objectForKey"recipe"];

    NSAssert(recipe, @"%s: Did not find recipe key in diction (%@)", __FUNCTION__, diction);

    [array addObject:recipe];
}

如果这些错误中的任何一个可能是生产中的运行时错误,您应该将 assert 语句替换为执行必要错误处理的 if 语句。但希望它能说明这个概念。

关于iphone - 无法在 Objective-C 中访问 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17516271/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4