Objective-C JSON - Convert JSON object to native o

2020-05-08 09:20发布

问题:

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

回答1:

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"];
 ... ... }


回答2:

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.