Objective-C JSON - 将JSON对象转换为本机对象? [英] Objective-C JSON - Convert JSON object to native object?

查看:373
本文介绍了Objective-C JSON - 将JSON对象转换为本机对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何提取每个 car JSON对象并将其放入原生对象?我正在使用 SBJSON 。这是我当前的代码,但它只能提取一个car元素,当我需要能够遍历每个car对象并保存它时:

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


推荐答案

尝试这样的理由..
当你执行 [[[request responseString] JSONValue] valueForKey:@list]]; 它会返回一个 cars <的列表数组/ code>。

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...

示例:

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

这篇关于Objective-C JSON - 将JSON对象转换为本机对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆