I am new to JSON and trying to make sense of the structure in order to parse some data from a web service.
As a model, I'm using code from an app tutorial that displays loans from Kiva. The code in the sample app is able to display a kiva loan from the following json output (I have cut out a lot as it displays a long list):
{"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":[]}]}
My json output looks like the following:
{"tasks":[{"row":{"userid":"1","task":"send email to Bob","longtask":"include attached memo"}}]}
How would I modify the objective-c below to work with my json with that structure.
Note: I basically have three levels to my json, the object "tasks", the row and the field values as in task: send email.
The kiva feed seems to have a paging thing at the beginning (that is a bit confusing) followed by the object "loans", no row level and then the field values as in name: harriet.
The kiva code has multiple fields show below. For my project, I just want to display a couple fields as in task and longtask.
Code in app tutorial:
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];
NSArray,NSDictionary,NSStringandNSNumber. If you understand all theses concept and can fetch into them even if nested, it's the same. You just have to understand what kind of object is at the wanted level.