Parse a Json Table to a NSMutableArray [duplicate]

与世无争的帅哥 提交于 2019-12-13 22:08:14

问题


for the moment I fill in my array directly by a native objective-C code :

Datas *pan1 = [[Datas alloc] initWithTitle:@"My array 1" title:@"Shakespeare's Book" location:@"London"];
Datas *pan2 = [[Datas alloc] initWithTitle:@"My array 2" title:@"Moliere's Book" location:@"London"];


  NSMutableArray *datasListe = [NSMutableArray arrayWithObjects:pan1, pan2, nil];

But I want to fill this NSMutableArray by this Json list :

{
    "myIndex" : [
              {
              "name":"My array 1",
              "title": "Shakespeare's Book",
              "location": "London"
              },
              {
              "name":"My Array 2",
              "title": "Moliere's Book",
              "location": "Paris"
              }
                ]
}

Anyone have ideas? Thanks much!


回答1:


This json data can be parse very easily like this.

NSError *e;
NSArray *dic= [NSJSONSerialization JSONObjectWithData: jsondata options:  NSJSONReadingMutableContainers error: &e];
NSMutableArray *datasListe = [[NSMutableArray alloc] init];
NSMutableArray *data = [dic objectForKey:@"myIndex"];
//Now you have array of dictionaries 
for(NSDictionary *dataDic in data){
NSString *name = [dataDic objectForkey:@"name"];
NSString *title = [dataDic objectForKey@"title"];
NSString *location = [dataDic objectForKey@"location"];
Datas *pan= [[Datas alloc] initWithTitle:name title:title location:location];
[dataList addObject:pan];
}



回答2:


NSDictionary *firstDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"Raja", @"name",
                            @"Developer", @"title",
                            @"USA", @"location",
                            nil];

  NSDictionary *secondDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"Deepika", @"name",
                            @"Engieer", @"title",
                            @"USA", @"location",
                            nil];

NSMutableArray * arr = [[NSMutableArray alloc] init];

[arr addObject:firstDictionary];
[arr addObject:secondDictionary];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(@"jsonArray as string:\n%@", jsonString);


来源:https://stackoverflow.com/questions/21218357/parse-a-json-table-to-a-nsmutablearray

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