ios - ObjectMapper如何映射[String :CustomObject] With Index as CustomObject Property的Dictionary

标签 ios json swift objectmapper

我这周开始使用 ObjectMapper,我正在尝试将 JSON 映射到 2 个 CustomClasses,但我不知道 ObjectMapper 是否具有某些功能来执行我想要的操作。第一个 CustomClass 具有类型属性:[String:CustomClass2],其中此词典的索引应为第二个 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"]
}

最佳答案

在您的 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"]
    }
}

关于ios - ObjectMapper如何映射[String :CustomObject] With Index as CustomObject Property的Dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44786731/

相关文章:

ios - 有阴影的 View

ios - 在openGL ES中检测距相机最近的顶点

javascript - 在 Web Api Controller 中将 JSON 反序列化为字典

json - 使用 Cloudformation Template 创建特定资源的多个实例

json - 如果字典中有多个 json 字段同名,如何获取值?

ios - NSPredicate 检查字符串长度

ios - tableView.reloadData() 只调用一次

ios - 需要帮助声明数组以在 Swift 3 中检索 plist 信息

json - 从 JSON Golang 读取 PGP key 时出现 EOF 错误

ios - 台风+swift自动注入(inject)