解析具有多个对象的JSON响应 [英] Parsing JSON response with multiple objects

查看:374
本文介绍了解析具有多个对象的JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a question regarding parsing a JSON response within iOS5.

当前,我正在遵循指南这里可以帮助我解析从第三方映射服务返回的JSON响应.

Currently, I'm following this guide here to help me parse the JSON response returned from a third-party mapping service.

一切正常,除了第三方服务器返回的JSON响应与指南本身所示的响应有所不同.

Everything works, except that the JSON response returned by the third-party server is somewhat different from the one shown in the guide itself.

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

In a nutshell, the overall structure of the entire JSON response looks something like this:

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

This is the actual JSON query URL.

使用这一行代码,

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

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

I am able to sucessfully get the jsonResponse dictionary to report that it has 3 key/value pairs, but my ultimate goal is to retrieve the array stored in 'routes.features.geometry.paths'.

这是我当前的代码块,它获得了数组值的最终集合:

This is my current code block that gets the final set of array values:

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];

我想知道是否有人对我应该如何以一种更优雅的方式做到这一点有更好的了解?

I was wondering if anyone might have a better idea of how I should go about doing this in a more elegant fashion?

非常感谢!

推荐答案

您不能仅将其用作JSON对象,因为它将作为JSON(纯字符串)运行,并且需要对其进行解析,以便为您解决问题这样做是为了直接进入路径

You can't just use it as JSON object because it will be working as JSON (Plain String) and you need to parse it so for your problem you can do like this to directly go to paths

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

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

Now you can access your paths data from "arr" array

更新:

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

因为features元素是一个数组,所以先遍历数组然后转到其元素

as features element is an Array so traverse array first then goto its elements

这篇关于解析具有多个对象的JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆