[英]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.