Fahim Parkar
Fahim Parkar

Reputation: 31627

how to add JSON data to an NSArray

I have json data as below.

[
    {"id":"2","imagePath":"image002.jpg","enDesc":"Nice Image 2"},
    {"id":"1","imagePath":"image001.jpg","enDesc":"Nice Image 1"}
]

I am assigning this to variable named NSArray *news.

Now I have three different array as below.

NSArray *idArray;
NSArray *pathArray;
NSArray *descArray;

I want to assign data of news to these arrays so that finally I should have as below.

NSArray *idArray = @["2","1"];
NSArray *pathArray = @["image002.jpg","image001.jpg"];
NSArray *descArray = @["Nice Image 2","Nice Image 1"];

Any idea how to get this done?


With the help of below answer this is what I did.

pathArray = [[NSArray alloc] initWithArray:[news valueForKey:@"imagePath"]];

I don't wanted to use NSMutableArray for some reasons.

Upvotes: 1

Views: 1980

Answers (4)

Prateek Prem
Prateek Prem

Reputation: 1544

Yes all the above ans is correct I am just integrating all of them together to be easly use to you:

NSArray *serverResponseArray = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil]; // I am assigning this json object to an array because as i show it is in array format.

now:

NSArray *idArray = [[NSMutableArray alloc] init];
NSArray *pathArray = [[NSMutableArray alloc] init];
NSArray *descArray = [[NSMutableArray alloc] init];
for(NSDictionary *news in serverResponseArray) 
{
   [idArray addObject:[news valueForKey:@"id"]];
   [pathArray addObject:[news valueForKey:@"imagePath"]];
   [descArray addObject:[news valueForKey:@"enDesc"]];
}

Upvotes: -1

x4h1d
x4h1d

Reputation: 6092

Load the json data into an NSDictionary, which you may call "news" . Then retrieve as

NSArray *idArray = [news valueForKeyPath:@"id"];
NSArray *pathArray = [news valueForKeyPath:@"imagePath"];
NSArray *descArray = [news valueForKeyPath:@"enDesc"];

Upvotes: 1

soryngod
soryngod

Reputation: 1827

Use this

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];

then you can extract all the information that you need from there you have NSArray that contains NSDictionary , where you can go and use objectForKey: to get all the info you need.

Upvotes: 2

Anton
Anton

Reputation: 2847

You should use JSONKit or TouchJSON to convert your JSON data to Dictionary. Than you may do this :

NSArray *idArray = [dictionary valueForKeyPath:@"id"]; // KVO

Upvotes: 2

Related Questions