ios - 在 Objective-C 中将 JSON 映射到 NSDictionary

标签 ios objective-c json mapping nsdictionary

我有来自网络服务的以下 JSON:

[
    "{
       "count":2,
       "offers":{
          "0":{
             "nodeID":"654321",
             "publicationDate":"1396272408",
             "title":"My first title",
             "locations":"New York City"
          },
          "1":{
             "nodeID":"123456",
             "publicationDate":"1396272474",
             "title":"My second title",
             "locations":"San Diego"
          }
       },
       "error":"null",
       "result":"success"
    }"
]

我需要将此 JSON 映射到 NSDictionary。我该怎么做?

我已经尝试过以下

NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&localError];

但它只给了我一本包含一个对象的字典。我需要访问 JSON 的所有字段,例如 "count""offers" 等。我该如何实现?

最佳答案

您的 JSON 输出不是字典而是数组。

NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSarray *parsedObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&localError];

for(NSDictionary *dict in parsedObject) {
   NSNumber *count = [dict objectForKey:@"count"];

}

但是 offer 节点很奇怪,作为数组会更好。

关于ios - 在 Objective-C 中将 JSON 映射到 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22863203/

相关文章:

objective-c - Objective C 没有抛出足够多的错误?

ios - 使用 SLComposeViewController 将图像发布到 Facebook

ios - 获取 '-[__NSArrayM city]: unrecognized selector sent to instance 0x111c03460' 错误

javascript - 保存为 cookie 时,JSON 编码数组转换为字符串

json - 检索 JSON 数据然后解析它(需要一些帮助)

Java 休息 Jersey : Posting multiple types of data (File and JSON)

ios - 调用 didSelectRowAtIndexPath 时 UIDetailView 不加载数据

ios - 尝试将 uiimageview 图像保存到变量中

ios - IBOutlets Strong or Weak - 它真的对内存管理有影响吗? (弧)

objective-c - 以编程方式创建 cocoa 应用程序的初始窗口(OS X)