iphone - 解析包含多个对象的 JSON 字符串

标签 iphone ios xcode json

我正在从 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:]: unrecognized selector sent to instance 0x1fd7cd10 * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x1fd7cd10' * First throw call stack: (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: terminate called throwing an exception (lldb)

最佳答案

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

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

关于iphone - 解析包含多个对象的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12998407/

相关文章:

iphone - 为运行 IOS4.2 的 iPad 关联文件类型的问题

ios - 我可以从企业帐户中删除应用程序 ID 并在标准开发人员帐户中重复使用吗

iOS应用程序拒绝2.1性能: APP COMPLETENESS

swift - 在范围内找不到类型 SwiftUI 'Color'

iphone - 如何从 NSUserDefaults 中取出字符串

ios - 从 plist 中的一组元素中获取唯一元素

ios - 修复 safari/iOS 上丢失的 unicode 符号

ios - xCode:iPad 的强制方向

ios - 构建成功后,应用程序启动没有返回有效的对,也没有在 Xcode 上返回启动错误

iPhone:漫游 MCC