如何在iOS中迭代JSON对象 [英] How to iterate JSON object in ios

查看:102
本文介绍了如何在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"]);

   }
}

这篇关于如何在iOS中迭代JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆