简体   繁体   中英

Parsing a nested json array

I need to parse the following nested json.

{  
   "status":1,
   "value":{  
      "details":[  
         {  
            "text":"this is test",
            "company":"General Marketing Company",
            "date":"05-DEC-15"
         },
         {  
            "text":"this is test2",
            "company":"NJ, Chennai",
            "date":"05-DEC-15"
         },
         {  
            "text":"Sample test message for welcome",
            "company":"sd",
            "date":"22-JAN-16"
         }
      ]
   }
}

Following is my code,

NSString* testimonialResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSData *jsonData = [testimonialResponse dataUsingEncoding:NSUTF8StringEncoding];

NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];

NSLog(@"Response %@",jsonDic[@"value"][@"details"]);

The above code can actually be able to parse the contents within details in general but it cant be able to parse each of those datas uniquely.say for instance, my code doesn't list all company names,texts,dates uniquely.

**You can use this**

 NSArray *array_details = [[jsonDic objectForKey:@"value"] objectForKey:@"details"];
 NSArray Compay_arr = [array_details valueForKey: @"company"];
 NSArray text_arr = [array_details valueForKey: @"text"];
 NSArray date_arr = [array_details valueForKey: @"date"];

do like

NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *dataArray = jsonDic[@"value"][@"details"];

 for (NSDictionary *tmp in dataArray)
{
 NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[tmp objectForKey:@"text"] forKey:@"text"];
[temp setObject:[tmp objectForKey:@"company"] forKey:@"company"];
[temp setObject:[tmp objectForKey:@"date"] forKey:@"date"];

  [yourArrayName addObject:temp];

}

EDit

if you want to stop here , use this

NSArray * finalAray = [NSArray arrayWithArray: jsonDic[@"value"][@"details"]]

What about :

NSString* testimonialResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSData *jsonData = [testimonialResponse dataUsingEncoding:NSUTF8StringEncoding];

NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];

NSArray * array = [NSArray arrayWithArray: jsonDic[@"value"][@"details"]]
NSArray *array = [NSArray arrayWithArray: jsonDic[@"value"][@"details"]];
NSArray *companyNames = [array valueForKey:@"company"];

companyNames contains all company names

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM