IOS JSON解析嵌套数据

时间:2013-10-29 21:13:08

标签: ios json nsdictionary

嗯,我想这是一个简单的问题(因为我最近才学习IOS)。

我见过的大多数教程都展示了简单的JSON键值示例。 但是我正在寻找一种具有以下格式的JSON结构:

所以我可以说一个JSON页面显示如下内容:

loans: (
    {
    activity = "Personal Products Sales";
    "basket_amount" = 0;
    "bonus_credit_eligibility" = 1;
    "borrower_count" = 1;
    description =         {
        languages =             (
            en
        );
    };
    "funded_amount" = 0;
    id = 623727;
    image =         {
        id = 1457061;
        "template_id" = 1;
    };
    "loan_amount" = 475;
    location =         {
        country = Philippines;
        "country_code" = PH;
        geo =             {
            level = country;
            pairs = "13 122";
            type = point;
        };
        town = "Maasin City, Leyte";
    };
    name = Zita;
    "partner_id" = 145;
    "planned_expiration_date" = "2013-11-28T21:00:02Z";
    "posted_date" = "2013-10-29T21:00:02Z";
    sector = Retail;
    status = fundraising;
    use = "to buy additional stocks of soap, toothpaste, dish washing products, etc.";
},

因此,例如,如果我想提取名称,我理解密钥对的想法,所以我只是做了类似的事情:

 NSError* error;
NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:responseData //1

                      options:kNilOptions
                      error:&error];

NSArray* latestLoans = [json objectForKey:@"loans"]; //2
 NSDictionary* loan = [latestLoans objectAtIndex:0];
NSString *name = [loan objectForKey:@"name"];

然后*名称应评估为:Zita。

但我的问题是......

1)为了获取结构内部的访问数据,我需要做什么样的技巧,例如“level = country;” (该级别位于“geo”内,位于“location”内)

有人可以解释一下如何做到这一点吗?

1 个答案:

答案 0 :(得分:3)

与你现在正在做的完全相同:)

NSDictionary* loan = [latestLoans objectAtIndex:0];
NSDictionary* location = [loan objectForKey:@"location"];
NSDictionary* geo = [locationobjectForKey:@"geo"];
NSString* level = [geo objectforKey:@"country"];

或更短:

NSDictionary* loan = [latestLoans objectAtIndex:0];
NSString* level = loan[@"location"][@"geo"][@"level"];