0
{"status": "FRE", "list": [{"make": "Toyota", "id": 1, "model": "camry", "engine": "Four Cylinder"}{"make": "Ford", "id": 3, "model": "focus", "engine": "Four Cylinder"}]}

How do I extract each "car" JSON object and put it into a native object? I'm using SBJSON. Here is my current code, but it is only able to extract one car element, when I need to be able to iterate through each car object and save it:

NSString *responseString = [request responseString];
     NSString *responseDict = [responseString JSONValue];

     NSArray *keys = [NSArray arrayWithObjects:@"id",@"make",@"model",@"engine", nil];
     NSArray *objects = [NSArray arrayWithObjects:[responseDict valueForKeyPath:@"list.make"],[responseDict valueForKeyPath:@"list.model"],[responseDict valueForKeyPath:@"list.id"],[responseDict valueForKeyPath:@"list.engine"] , nil];

     self.car = [[NSDictionary alloc]initWithObjects:objects forKeys:keys];

2 Answers 2

9

Instead of doing everything manually, use Jastor - https://github.com/elado/jastor You just need to create simple classes and initWithDictionary will do the entire assigning work for you.

Sign up to request clarification or add additional context in comments.

Comments

2

Try to reason like this.. when you do [[[request responseString] JSONValue] valueForKey:@"list"]]; it will return an array of list of your cars.

Then you iterate each array and save it into your car element...

Example:

NSArray *arrayCar =  [NSArray arrayWithArray:[[[request responseString] JSONValue] valueForKey:@"list"]];


for (NSDictionary *carDict in arrayCar) {
Car car = [[Car alloc] init]; 
car.id = [carDict valueForKey:@"id"]; 
car.origin= [carDict valueForKey:@"make"];
 ... ... }

4 Comments

Works great. I just wasn't quite getting it, but understand now completely.
Any special resaon for using arrayWithArray: even when list should be an array? Does it check type?
No it does not check type, I gave an example of an array referring to the example given above.. If not, i normally do a class check : if ([[[request responseString] JSONValue] valueForKey] isKindOfClass:[NSArray class]) .. else if ([[[request responseString] JSONValue] valueForKey:@"list"] isKindOfClass:[NSString class]] ...
You need to know what kind of format you will receive and you will treat in the client's side.. and treat all the case possible, for example if i'm getting [[[request responseString] JSONValue] valueForKey:@"FRE"], it will return an NSDictionary instead of NSArray

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.