如何在iOS中迭代JSON对象

问题描述:

我这样创建json对象

I create json object like this

id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

但是该文档没有告诉我如何通过键和值来循环json对象.

But the document does not tell me how to loop the json object by keys and values.

这里是一种方法.如果您提出更具体的问题,我们将很乐意为您提供更多详细信息.

Here is one way to do it. I'll be happy to get into more details if you make your question more specific.

    NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *e = nil;
    NSArray *jsArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];

if (!jsArray) {
  NSLog(@"Error parsing JSON: %@", e);
} else {
   for(NSDictionary *item in jsArray) {
      NSLog(@"Item: %@", item);
      NSLog(@"%@",[item objectForKey:@"id"]);
      NSLog(@"%@",[item objectForKey:@"name"]);

   }
}