如何在objective-C中的集合中提取嵌套的JSON值? [英] How can I pull out nested JSON values in a collection in objective-C?

查看:115
本文介绍了如何在objective-C中的集合中提取嵌套的JSON值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以返回对象集合的JSON值的OData服务。我想将一个iPhone应用程序指向该服务的JSON对象集合(结果如下所示,带有一个样本记录)。

I've got an OData service that can return JSON values for an object collection. I'd like to point an iPhone app at a collection of JSON objects off of that service (results shown below with one sample record).

我该怎么办?解析这些嵌套值?当我将响应字符串转换为JSON值时,它只会抓取d(我的代码也在下面)。

How can I parse these nested values? When I convert the response string to JSON values, it only grabs "d" (my code for that is also below).

{
"d" : {
"results": [
{
"__metadata": {
"uri": "http://someserver/service.svc/collection(1234L)", "type": "My.Namespace.Type"
}, "Property1": "value1", "Property2": 7274, "Collection1": {
"__deferred": {
"Property3": "http://someserver/service.svc/collection(1234L)/Images"
}
}
},
...

示例目标C代码:

- (void)requestFinished:(ASIHTTPRequest *)request
{
    if (request.responseStatusCode == 200)
    {
        NSString *responseString = [request responseString];

        textView.text = responseString;

        NSDictionary *responseDict = [responseString JSONValue];
        NSArray *keys = [responseDict allKeys];

        [self printArray:keys]; // This prints "d"
        ...
     }
}


推荐答案

似乎你有一个根键d而所有的键实际上都是子键,试试

It seems that you have a root key "d" and all the keys are in fact subkeys, try

NSDictionary *responseDict = [[responseString JSONValue] objectForKey:@"d"];

甚至

NSArray *responseArray = [[[responseString JSONValue] objectForKey:@"d"] objectForKey:@"results"];

这是NSArray和NSDictionnary的替代:

it's an alternance of NSArray and NSDictionnary :

NSDictionary *responseDict = [[responseString JSONValue] valueForKey:@"d"];
NSArray *responseArray = [responseDict valueForKey:@"results"];

NSDictionary *dict;
for(int i=0; i< [responseArray count]; i++){
    dict = [responseArray objectAtIndex:i];
    NSLog(@"- %@",[responseArray objectAtIndex:i]);

}

它总是强烈依赖于你的JSON生成器即可。所以我无法确定它总是最好的挖掘方式,但在这种情况下似乎是这样。请记住:

it's always strongly dependant on your JSON generator. So I cannot tell you for sure it's always the best way of digging, but in this case it seems so. Just remember:


  • [data1,data2,data3,data4] - > array

  • {key1 :data1,key2:data2} - >字典

这篇关于如何在objective-C中的集合中提取嵌套的JSON值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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