Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON dictionary / array

If a JSON web service returns something like this (details of houses)

[
    {
        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
    }
]

How would I iterate thru each house one-by-one? I'm using ASIHTTPRequest and the JSON parser: http://stig.github.com/json-framework/

I think I can get the dictionary like so:

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

.. but I'm unsure how to iterate thru each house.

like image 499
cannyboy Avatar asked Jan 21 '23 00:01

cannyboy


1 Answers

{
        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
    }

This is array of dictionaries... you can create a Modal class of you House(attributed :id,price,location,size) and iterate it as follows...(considering you finally have above thing)..

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

Thanks,

like image 180
Ravin Avatar answered Jan 30 '23 06:01

Ravin