gpt4 book ai didi

ios - 如何在 Obj-C 中解析 JSON

转载 作者:行者123 更新时间:2023-11-29 01:52:57 27 4
gpt4 key购买 nike

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

作为模型,我使用应用程序 tutorial 中的代码显示来自 Kiva 的贷款。示例应用程序中的代码能够从以下 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 代码有多个字段,如下所示。对于我的项目,我只想显示几个字段,如 task 和 longtask。

应用教程中的代码:

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

最佳答案

我用代码解析了你的输出 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];
}

关于ios - 如何在 Obj-C 中解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31210512/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com