2011-04-13 240 views
4

如果一個JSON Web服務將返回這樣的事情(房屋的詳細信息)解析JSON字典/陣列

[ 
    { 
     id:4, 
     price: 471, 
     location: "New York", 
     size: 3000 
    }, 
    { 
     id:7, 
     price: 432, 
     location: "London", 
     size: 3200 
    }, 
    { 
     id:22, 
     price: 528, 
     location: "Tokyo", 
     size: 2000 
    } 
] 

我怎麼會遍歷直通每家一個接一個?我使用ASIHTTPRequest和JSON解析器:http://stig.github.com/json-framework/

我想我可以得到字典,像這樣:

NSString *theResponse = [request responseString]; 
NSDictionary *dictionary = [theResponse JSONValue]; 

..但我不能確定如何遍歷每個直通房子。

+0

看看這個解析器https://github.com/johnezang/JSONKit。它將JSON記錄轉換爲Objective-C對象,類似於NSPropertyListSerialization處理plists的方式。而且,速度非常快。 – 2011-04-13 16:51:53

回答

9
{ 
     id:4, 
     price: 471, 
     location: "New York", 
     size: 3000 
    }, 
    { 
     id:7, 
     price: 432, 
     location: "London", 
     size: 3200 
    }, 
    { 
     id:22, 
     price: 528, 
     location: "Tokyo", 
     size: 2000 
    } 

這是字典的陣列...你可以創建一個模式類的,你家(歸屬:ID,價格,位置,大小),如下重複它......(考慮你終於有上述事情)..

NSArray *houses = [dictionary objectForKey:<youHaveNotProvideItInYourData>]; 
NSMutableArray *populatedHouseArray = [[NSMutableArray alloc]init]; 
for(int i=0;i<[houses count];i++) 
{ 
    NSDictionary *tempDictionary = [houses objectAtIndex:i]; 
    House *tempHouse = [[House alloc]init]; 
    if([tempDictionary objectForKey:@"id"]!=nil 
    { 
    tempHouse.id = [tempDictionary objectForKey:@"id"]; 
    } 
    //and so on for other keys 

    [populatedHouseArray addObject:tempHouse]; 
    [tempHouse release]; 
} 

感謝,

+0

感謝您的評價。可否請您澄清一下,如果您是否處理了人口密集的房屋陣列中的單個房屋? – 2013-02-02 04:56:10