使用 ObjectMapper (https://github.com/Hearst-DD/ObjectMapper),我正在JSON
转换为Swift
个对象。访问user.profession
时应用崩溃了。
基本上,我不知道如何使用相同的JSON映射根节点解析模型中的另一个可映射对象,我认为这样做错了。我无法在任何地方找到相同的文档。
JSON词典:
user: {
"name": "Dinesh",
"url": "https://dinaraja.me",
"company": "IIINC",
"designation": "Developer"
}
型号:
struct User: Mappable {
var name: String!
var url: URL!
var profession: Profession!
init(_ map: Map) {
name <- map["name"]
url <- map["url"]
profession <- map // FIXME: It's not working. Find out what we do here is right/wrong
}
}
struct Profession: Mappable {
var company: String!
var designation: String!
init(_ map: Map) {
company <- map["company"]
designation <- map["designation"]
}
}
我做了什么:
let user = Mapper<User>().map(myJSONDictionary)
print(user.profession.company) //FIXME: Crashes here
任何帮助都将不胜感激。
答案 0 :(得分:1)
由于profession
模型未直接包含在user
json模型中,因此在这种情况下不应使用对象映射器<-
运算符。相反,您应该直接从Profession
映射函数
user
对象
struct User: Mappable {
var name: String!
var url: URL!
var profession: Profession!
init(map: Map) {
}
mutating func mapping(map: Map) {
name <- map["name"]
url <- map["url"]
profession = Profession(map: map)
}
}
struct Profession: Mappable {
var company: String!
var designation: String!
init(map: Map) {
company <- map["company"]
designation <- map["designation"]
}
mutating func mapping(map: Map) {
company <- map["company"]
designation <- map["designation"]
}
}