【问题标题】:Parsing JSON String containing multiple objects解析包含多个对象的 JSON 字符串
【发布时间】:2012-10-21 13:50:15
【问题描述】:

我正在从 url 检索 json 数据。 json“字符串”有一个对象,其中包含多个对象,每个对象都包含自己的键、值属性……本质上,json对象是一个包含或多或少是字典对象的对象的NSArray。我正在尝试使用 NSJSONSerialization 但没有很多文档,而且我似乎无法弄清楚如何使用以下是 json 的示例:

{"allObjects":[{"firstName":"homer","middleName":"j","lastName":"simpson"
,"address": "123 evergreen terrace","countryCode":"US","zip":12345},
{"firstName": "marge","middleName":"b","lastName":"simpson","address":
"123 evergreen terrace","countryCode":"US","zip":12345}]}

(如果重要,JSON 对象包含更多条目)

我需要与 NSJSONSerialization 一起使用特定的“选项”来获取字典数组(数组为“allObjects”)吗?

任何帮助将不胜感激!

提前致谢。

更新

此代码导致错误:

@vishy 我也是这么想的,但是当我运行这段代码时,

NSArray *json = [NSJSONSerialization JSONObjectWithData:geoNamesJSON options: kNilOptions error:&error];
NSDictionary *dict = [json objectAtIndex:0];
NSArray *allKeys = [dict allKeys];
NSString *key = [[NSString alloc] init];
NSEnumerator *keyEnum = [allKeys objectEnumerator];
NSLog(@"All keys in the first dictionary object:");
while(key = [keyEnum nextObject]){
    NSLog(@"%@", key);}

我收到此错误:

-[__NSCFDictionary objectAtIndex:]:无法识别的选择器发送到实例 0x1fd7cd10 * 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[__NSCFDictionary objectAtIndex:]: 无法识别的选择器发送到实例 0x1fd7cd10' * 第一次抛出调用栈:(0x3796c2a3 0x35c7c97f 0x3796fe07 0x3796e531 0x378c5f68 0xf310b 0xf219d 0x38ca4321 0x38cdecfd 0x38d53cc1 0x38cd86a7 0x38cd8481 0x38c52abb 0x38cc78d7 0x355b9bd9 0x3665c4b7 0x366611bd 0x3793ff3b 0x378b2ebd 0x378b2d49 0x37def2eb 0x38c91301 0xd3551 0x3c39db20) libc++abi.dylib: 终止调用抛出一个 异常(lldb)

【问题讨论】:

  • 在给定的json中-它是一个字典,其中有一个对象,它们是2个字典的数组。要解析任何json,您应该知道您的json的格式,然后只有您可以编写你的解析代码..
  • @vishy 我使用这种方法更新了我的问题(无法弄清楚迷你 Markdown)。

标签: iphone ios xcode json


【解决方案1】:

执行此步骤后,您是否在数组中获取任何值

NSArray *json = [NSJSONSerialization JSONObjectWithData:geoNamesJSON options:kNilOptions error:&error]; 

我不这么认为,因为您的 json 是一本字典。应该是

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:geoNamesJSON options:kNilOptions error:&error];

有关处理 json 的信息,您可以关注此tutorial

编辑:使用上面几行得到json字典后这样解析数据

NSArray* geoList = [geoDict objectForKey:@"geonames"];
NSLog(@"first object in geolist--%@",[geoList objectAtIndex:0]);
//each object in the array is a dictionary

【讨论】:

  • 当您在序列化后获取字典时,您可以打印并检查它的格式..您可以显示数据日志吗..?
  • geonames = ( { adminCode1 = OMITTED adminName1 = OMITTED countryCode = OMITTED countryName = OMITTED i> 距离 = "OMITTED"; fcl = OMITTED; fclName = "OMITTED"; fcode = OMITTED; fcodeName = OMITTED; geonameId = OMITTED; lat = "OMITTED"; lng = "OMITTED"; name = "OMITTED"; 人口 = 0; 地名名称 = OMITTED; });
  • 这里的'='是什么.. & wat 是'geonames' 根据这个json只有一个字典,它作为字符串(对象)和键..
  • 我只是按照你的要求做了。首先我做了: NSDictionary *json = [NSJSONSerialization JSONObjectWithData:geoNamesJSON options: kNilOptions error:&error]; NSLog(@"%@", json);
  • 我有一些疑问...检查我上面的 cmets
猜你喜欢
  • 2021-08-04
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多