簡體   English   中英

Objective-C JSON-將JSON對象轉換為本地對象?

[英]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"}]}

如何提取每個“ carJSON 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM