[英]Objective-C JSON - Convert JSON object to native object?
{"status": "FRE", "list": [{"make": "Toyota", "id": 1, "model": "camry", "engine": "Four Cylinder"}{"make": "Ford", "id": 3, "model": "focus", "engine": "Four Cylinder"}]}
如何提取每个“ car
” JSON object
并将其放入本机object
? 我正在使用SBJSON 。 这是我当前的代码,但是当我需要能够遍历每个汽车对象并保存它时,它只能提取一个汽车元素:
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];
无需手动完成所有操作,而使用Jastor- https://github.com/elado/jastor您只需要创建简单的类, initWithDictionary
将为您完成整个分配工作。
当您执行[[[request responseString] JSONValue] valueForKey:@"list"]];
时,尝试尝试这样的推理[[[request responseString] JSONValue] valueForKey:@"list"]];
它将返回您的cars
列表的数组。
然后,您迭代每个array
并将其保存到您的car
元素中...
例:
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"];
... ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.