【问题标题】:ObjectMapper how map Dictionary of [String:CustomObject] With Index as CustomObject PropertyObjectMapper 如何以索引为 CustomObject 属性映射 [String:CustomObject] 的字典
【发布时间】:2017-06-27 17:47:28
【问题描述】:

本周我开始使用 ObjectMapper,我正在尝试将 JSON 映射到 2 个 CustomClasses,但我不知道 ObjectMapper 是否有一些功能可以做我想做的事情。第一个 CustomClass 的属性类型为:[String:CustomClass2],其中此 Dictionary 的索引应该是第二个 CustomObject 的属性 ID。

使用的 JSON:

{ 
  "types": [
   { 
    "id": "mk8QPMSo2xvtSoP0cBUD",
    "name": "type 1",
    "img": "type_1",
    "showCategories": false,
    "modalityHint": [
      "K7VqeFkRQNXoh2OBxgIf"
    ],
    "categories": [
      "mP3MqbJrO5Da1dVAPRvk",
      "SlNezp2m3PECnTyqQMUV"
    ]
   }
  ]
}

使用的类:

class MyClass: Mappable {
    var types:[String:MyClass2] = [String:MyClass2]() //Index should be ID property of MyClass2 Object
    required init?(map:Map) {
        guard map.JSON["types"] != nil else {
            return nil
        }
    }
    func mapping(map: Map) {
        types <- map["types"]
    }
}
class MyClass2: Mappable {
    private var id: String!
    private var name: String!
    private var img: String!
    private var showCategories: Bool!
    private var modalityHint: [String]?
    private var categories: [String]?
    required init?(map: Map) { }
    func mapping(map: Map) {
        id <- map["id"]
        name <- map["name"]
        img <- map["img"]
        showCategories <- map["showCategories"]
        modalityHint <- map["modalityHint"]
        categories <- map["categories"]
}

【问题讨论】:

  • 我认为类型不应该是[String:Class2],而应该是[Class2]

标签: ios json swift objectmapper


【解决方案1】:

在您的 JSON 中,types 键是 array 而不是 Dictionary

变化:

var types:[String:MyClass2] = [String:MyClass2]()

收件人:

var types:[Class2] = []

像这样:

class MyClass: Mappable {
    private var arrayTypes = [MyClass2] {
        didSet{
            var mapTypes = [String:MyClass2]?
            for obj in arrayTypes {
                mapTypes[obj.id] = obj
            }

            types = mapTypes
        }
    }

    var types:[String:MyClass2] = [String:MyClass2]()
    required init?(map:Map) {
        guard map.JSON["types"] != nil else {
            return nil
        }
    }
    func mapping(map: Map) {
        arrayTypes <- map["types"]
    }
}

【讨论】:

  • 是的,我的 json 结构与我的 Class 结构不同,但有没有办法使用 ObjectMapper 函数进行这种转换?
  • 那么你想将它映射到一个字典中,使用 id 值作为字典中的键?
  • 是的,完全正确。不知道有没有可能?
  • 不是直接你必须将响应映射到一个单独的私有变量中的数组,然后在该属性的 didSet 上循环它并将每个 id 映射到 MyClass2 并将其设置为类型。跨度>
猜你喜欢
  • 2016-11-15
  • 2019-08-03
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多