how to add JSON data to an NSArray

旧城冷巷雨未停 提交于 2020-01-05 10:10:33

问题


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.


回答1:


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

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



回答2:


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.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/17470876/how-to-add-json-data-to-an-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!