gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:17:11 24 4
gpt4 key购买 nike

我这周开始使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com