This question already has an answer here:
-
Parsing Json to get all the contents in one NSArray
1 answer
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!
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];
}
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);