【问题标题】:How to map dictionary with dynamic keys with ObjectMapper?如何使用 ObjectMapper 映射字典与动态键?
【发布时间】:2019-03-13 11:53:36
【问题描述】:

我是 ObjectMapper 的新手。我收到了服务器的回复:

{
      "123123": 10,
      "435555": 2,
      "435333": 8,
      "567567": 4
}

键(动态)将是 ID。值将是 COUNT。如何使用 ObjectMapper 映射它?

我的代码不起作用,因为动态键:

extension Item: Mappable {

    private static let kId = "id"
    private static let kCount = "count"

    public init?(map: Map) {
        self.init()
    }

    mutating public func mapping(map: Map) {

        id <- map[Item.kId]
        count <- map[Item.kCount]
    }
}

【问题讨论】:

  • 我觉得,ObjectMapper 将无法为您提供帮助,因为它将是动态 Id。为什么不能为这种情况创建自定义类/结构/简单字典。

标签: ios swift objectmapper


【解决方案1】:

你的响应是一个对象,你可以通过map.JSON访问它,它的类型是[String: Any]。然后你可以像普通的Dictionary 一样使用它。

在这里,我创建了一个名为 Model 的类,其中包含项目数组(Item 类型),在 func mapping(:Map) 中,我将 map.JSON 元素映射到 Item。

class Model: Mappable {
    typealias Item = (id: String, count: Int)
    var items: [Item] = []

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        let rawDictionary = map.JSON
        let items = rawDictionary.compactMap { (key, value) -> Item? in
            guard let intValue = value as? Int else { return nil }
            return (key, intValue)
        }
        self.items = items
    }
}

let jsonString = """
{
    "123123": 10,
    "435555": 2,
    "435333": 8,
    "567567": 4
}
"""

let model = Model(JSONString: jsonString)
print(model?.items[0])  //Optional((id: "123123", count: 10))

【讨论】:

    【解决方案2】:

    你可以试试

     do{
    
        let res = try JSONDecoder().decode([String:Int].self, from: data)
    
    }
    catch {
    
        print(error)
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 2022-01-10
      • 2021-06-17
      相关资源
      最近更新 更多