【问题标题】:Parsing JSON response with multiple objects使用多个对象解析 JSON 响应
【发布时间】:2012-01-26 01:33:49
【问题描述】:

我有一个关于在 iOS5 中解析 JSON 响应的问题。

目前,我正在关注this 指南,以帮助我解析从第三方映射服务返回的 JSON 响应。

一切正常,只是第三方服务器返回的 JSON 响应与指南本身显示的有所不同。

简而言之,整个 JSON 响应的整体结构如下所示:

{  
    "directions": [....],  
    "messages": [....],  
    "routes":  
        {  
            "features": [  
                {  
                    "attributes": {....},  
                    "geometry":  
                        {  
                            "paths": [....]  
                        }  
                }  
            ]  
        }  
}  

This 是实际的 JSON 查询 URL。

通过使用这行代码,

NSDictionary * jsonResponse = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

我能够成功获取 jsonResponse 字典以报告它具有 3 个键/值对,但我的最终目标是检索存储在“routes.features.geometry.paths”中的数组。

这是我当前获取最后一组数组值的代码块:

NSDictionary * jsonResponse = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

NSArray * jsonArray = [jsonResponse valueForKeyPath:@"routes.features.geometry.paths"];

jsonArray = [jsonArray objectAtIndex:0];
jsonArray = [jsonArray objectAtIndex:0];

我想知道是否有人可以更好地了解我应该如何以更优雅的方式进行此操作?

提前非常感谢!

【问题讨论】:

    标签: ios json


    【解决方案1】:

    您不能只将它用作 JSON 对象,因为它将作为 JSON(纯字符串)工作,您需要对其进行解析,因此对于您的问题,您可以这样做直接转到路径

    NSArray *arr = [[[[jsonResponse objectForKey:@"routes"] objectForKey:@"features"] objectForKey:@"geometry"] objectForKey:@"paths"];
    

    现在您可以从“arr”数组访问路径数据

    更新:

    NSArray *arr = [[[[[jsonResponse objectForKey:@"routes"] objectForKey:@"features"] objectAtIndex:0] objectForKey:@"geometry"] objectForKey:@"paths"];
    

    由于特征元素是一个数组,所以先遍历数组然后转到它的元素

    【讨论】:

    • 不幸的是,当我这样做时出现错误:*** 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0xa0ce660'
    • [[[[[jsonResponse objectForKey:@"routes"] objectForKey:@"features"] objectAtIndex:0] objectForKey:@"geometry"] objectForKey:@"paths"];我想这会运行,因为我再次看到了 json,并且您的“功能”节点包含一个数组,然后遍历到 Dictionary。
    • 检查 json 是否有 Dictionary 或 Array 的快速注释,如果您在任何元素处遇到此字符“[”,则该元素将作为 Array 遍历,如果您在任何元素处发现“{”元素将作为字典遍历
    • 对更新后的代码稍作修改即可完美运行,非常感谢! NSArray * jsonArray = [[[[[[jsonResponse objectForKey:@"routes"] objectForKey:@"features"] objectAtIndex:0] objectForKey:@"geometry"] objectForKey:@"paths"] objectAtIndex:0];跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    相关资源
    最近更新 更多