• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

iphone - 无法在 Objective-C 中访问 JSON 数据

[复制链接]
菜鸟教程小白 发表于 2022-12-13 03:04:06 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

好的,这是我在 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap