如何从json字符串中检索数据

时间:2017-01-24 20:19:59

标签: ios objective-c json

[
  {
    "c_name" : "r",
    "email_id" : "r",
    "phn_no" : "2",
    "c_id" : "1"
  },
  {
    "c_name" : "e",
    "email_id" : "e",
    "phn_no" : "4",
    "c_id" : "2"
  }
]

这是我作为JSON字符串收到的输出。现在我该如何访问这些数据?我使用了NSJSONSerialization类:

NSError *writeError = nil;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr_mcontacts options:NSJSONWritingPrettyPrinted error:&writeError];

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSLog(@"JSON Output: %@",jsonString);

2 个答案:

答案 0 :(得分:1)

我认为你有一系列词典。这样的事情应该有效:

NSError *writeError;
NSError *error;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *arrayOfDictionary = [[NSMutableArray alloc] init];
arrayOfDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

NSDictionary *dictionary = [myArray objectAtIndex:0];
NSString *valueString= [dictionary objectForKey: @"c_name"];

答案 1 :(得分:0)

要访问数据,请使用字典而不是字符串。以下代码显示

NSDictionary *responseDict=[NSJSONSerialization JSONObjectWithData: jsonData options:NSJSONReadingMutableContainers error:&error]; for(NSArray *a in responseDict) {[cnamearray addobject [a valueforKey:@"c_name"]]; }NSLog(@"The cnamearray contains:", cnamearray);

输出将是cnamearray包含:{r,e}