Reputation: 4727
{"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];
Upvotes: 0
Views: 11196
Reputation: 298
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"];
... ... }
Upvotes: 2
Reputation: 8740
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.
Upvotes: 9