如何在Obj-C中解析JSON

时间:2015-07-03 15:50:39

标签: ios objective-c json

我是JSON的新手并试图理解结构,以便从Web服务中解析一些数据。

作为一个模型,我使用来自Kiva贷款的应用tutorial中的代码。示例应用程序中的代码能够显示来自以下json输出的kiva贷款(因为它显示了很长的列表,我已经剪掉了很多):

{"paging":{"page":1,"total":6446,"page_size":20,"pages":323},"loans":[{"id":910788,"name":"Harriet","description":{"languages":["en"]},"status":"fundraising","funded_amount":0,"basket_amount":0,"image":{"id":1918586,"template_id":1},"activity":"Poultry","sector":"Agriculture","themes":["Vulnerable Groups","Youth"],"use":"to buy birds, feed, and vaccines.","location":{"country_code":"UG","country":"Uganda","town":"Zanna","geo":{"level":"town","pairs":"2 33","type":"point"}},"partner_id":65,"posted_date":"2015-07-03T15:30:02Z","planned_expiration_date":"2015-08-02T15:30:02Z","loan_amount":250,"borrower_count":1,"lender_count":0,"bonus_credit_eligibility":true,"tags":[]}]}

我的json输出如下所示:

{"tasks":[{"row":{"userid":"1","task":"send email to Bob","longtask":"include attached memo"}}]}

如何修改下面的objective-c以使用具有该结构的json。

注意:我的json基本上有三个级别,对象"任务",行和字段值,如任务:发送电子邮件。

kiva feed似乎在开始时有一个分页事件(这有点令人困惑),其次是对象"贷款",没有行级别,然后是字段值,如名称:harriet。

kiva代码有多个字段如下所示。对于我的项目,我只想在任务和长任务中显示几个字段。

应用教程中的代码:

 NSArray* latestLoans = [json objectForKey:@"loans"]; //2
    // 1) Get the latest loan
    NSDictionary* loan = [latestLoans objectAtIndex:0];

    // 2) Get the funded amount
    NSNumber* fundedAmount = [loan objectForKey:@"funded_amount"];

    // 3) Set the label appropriately
    humanReadble.text = [NSString stringWithFormat:@"Latest loan: %@ from %@ has raised $%.2f to pursue their entrepreneural dream",
                         [loan objectForKey:@"name"],
                         [(NSDictionary*)[loan objectForKey:@"location"] objectForKey:@"country"],
                         fundedAmount
                         ];

    //build an info object and convert to json
    NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
                          [loan objectForKey:@"name"], @"who",
                          [(NSDictionary*)[loan objectForKey:@"location"] objectForKey:@"country"], @"where",
                          [NSNumber numberWithFloat: fundedAmount], @"what",
                          nil];

1 个答案:

答案 0 :(得分:1)

我用代码解析了你的输出JSON:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"nameofilejson" ofType:@".json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"%@",json); 
NSMutableArray *getElement = [json objectForKey:@"tasks"];
for (NSDictionary *dict in getElement) {
    NSArray *array = [dict objectForKey:@"row"];
    NSString *str = [array objectAtIndex:0];
}