解析嵌套的json数组

时间:2016-02-18 10:13:24

标签: ios objective-c json

我需要解析以下嵌套的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"
         }
      ]
   }
}

以下是我的代码,

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

上面的代码实际上可以解析详细信息中的内容,但是它无法唯一地解析每个数据。例如,我的代码没有列出所有公司名称,文本,日期唯一。

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

喜欢

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

}

修改

如果你想在此停止,请使用此

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

答案 2 :(得分:1)

怎么样:

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

答案 3 :(得分:1)

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

companyNames包含所有公司名称