【问题标题】:ObjectMapper: Dictionary key as value in Mapped objectsObjectMapper:字典键作为映射对象中的值
【发布时间】:2017-10-05 05:15:52
【问题描述】:
{
  "3": {
    "title": "something"
  },
  "28": {
    "title": "something else"
  }
}

如何使用 ObjectMapper 将此 json 转换为 Content 对象数组?

struct Content: Mappable {
    var id: String? //Expected value is 3, 28
    var title: String? //Expected value is "something", "something else"
}

提前致谢。

【问题讨论】:

    标签: ios json swift objectmapper


    【解决方案1】:

    我认为您正在寻找这样的东西:

    JSON - 模型:

    let content = Mapper<Content>().map(JSONString)
    

    模型 - JSON:

    let json = Mapper().toJSONString(content, prettyPrint: true)
    

    在您可以使用它之前,您需要将您的 Content Model 更改为以下内容:

    struct Content: Mappable {
        var id: String? //Expected value is 3, 28
        var title: String? //Expected value is "something", "something else"
    
        required init?(_ map: Map) {
    
        }
    
        // Mappable
        func mapping(map: Map) {
            id <- map["id"]
            title <- map["title"]
        }
    }
    

    【讨论】:

      【解决方案2】:

      在 Swift 3 中: 首先像这样从这个字典中获取所有的键

      keysArray = Array(dict.keys)
      

      现在遍历这个keysArray&你会从这个字典中得到所有的键

      for i in 0..<keysArray.count {
          if let key = keysArray[i] as? String {
             //get your key here
              if let singleObject = dict[key] as? [String: Any] {
                 if let value = singleObject["title"] as? String {
                    //get you value
                    // get both key & value. Now map it. Hope you get it.
                 }
              }
          }
      }
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2019-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        • 2016-11-15
        • 1970-01-01
        • 2018-04-29
        • 2011-12-27
        相关资源
        最近更新 更多