【问题标题】:Map JSON to NSDictionary in Objective-C在 Objective-C 中将 JSON 映射到 NSDictionary
【发布时间】:2014-05-16 18:59:03
【问题描述】:

我有以下来自 Web 服务的 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" 等。我该如何实现?

【问题讨论】:

    标签: ios objective-c json mapping nsdictionary


    【解决方案1】:

    你的 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节点很奇怪,作为一个数组会更好。

    【讨论】:

    • 感谢您的回答。它工作正常。你是对的,这看起来很奇怪,我会尝试改变它。
    • 除了奇怪的花括号外,这实际上是有效的 JSON 吗?封装 JSON 对象的方括号看起来也很奇怪,不是吗?
    • 如果您只返回一个对象,那么可以。以您为例,它看起来确实很奇怪且不需要。
    【解决方案2】:

    以这种形式获取您的数据...您的 json 给出错误“.....

       [
          {
               "count": 2,
               "offers":
               {
               "0": {
                         "nodeID": "654321",
                         "publicationDate": "1396272408",
                         "title": "Myfirsttitle",
                         "locations": "NewYorkCity"
                    },
               "1": {
                         "nodeID": "123456",
                         "publicationDate": "1396272474",
                         "title": "Mysecondtitle",
                         "locations": "SanDiego"
                    }
               },
               "error": "null",
               "result": "success"
          }
       ]
    

    您在数组中获取数据 [ 字典中有字典 ....

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 2011-11-07
      • 2011-08-09
      • 2012-02-13
      • 1970-01-01
      • 2016-04-12
      • 2013-09-12
      • 2012-01-08
      • 1970-01-01
      相关资源
      最近更新 更多