0

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];
2
  • JSON is made in terms of Objective-C of NSArray, NSDictionary, NSString and NSNumber. 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. Commented Jul 3, 2015 at 16:10
  • 1
    In this case, you have a dictionary because of the { with a single element with a key "tasks". "tasks" has a value that is an array because of the [ . That array again contains a single dictionary, with a key "row". And the value for that key is another dictionary, this time with three keys userid, task, and longtask. Commented Jul 3, 2015 at 16:46

1 Answer 1

1

I parsed your output JSON with code:

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

NSLog prints out the json but then get an error when it tries to find objectAtIndex:0 as follows: 2015-07-04 14:56:37.811 KivaJSONDemo[15888:7523592] -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x7d93d770 2015-07-04 14:56:37.813 KivaJSONDemo[15888:7523592] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x7d93d770' *** First throw call stack:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.