如何使用Codable
协议解码部分双序列化json字符串?
class Person : Codable {
var name : String?
var hobby : String?
}
class Family : Codable {
var person: String?
var person_: Person?
}
class PerfectFamily : Codable {
var person: Person?
}
let jsonString = "{\"person\":\"{\\\"name\\\":\\\"Mike\\\",\\\"hobby\\\":\\\"fishing\\\"}\"}"
do {
// I could do this.
let family = try JSONDecoder().decode(Family.self, from: Data(jsonString.utf8))
family.person_ = try JSONDecoder().decode(Person.self, from: Data(family.person!.utf8))
print(family)
// However I want to write more simply like this. Do you have some idea?
let perfectFamily = try JSONDecoder().decode(PerfectFamily.self, from: Data(jsonString.utf8)) // error
print(perfectFamily)
} catch {
print(error)
}
答案 0 :(得分:2)
如果您无法修复双重编码的json,您可以为PerfectFamily类提供自己的自定义解码器方法,但我建议使用结构:
struct Person: Codable {
let name: String
let hobby: String
}
struct PerfectFamily: Codable {
let person: Person
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let person = try container.decode([String: String].self)["person"] ?? ""
self.person = try JSONDecoder().decode(Person.self, from: Data(person.utf8))
}
}
let json = "{\"person\":\"{\\\"name\\\":\\\"Mike\\\",\\\"hobby\\\":\\\"fishing\\\"}\"}"
do {
let person = try JSONDecoder().decode(PerfectFamily.self, from: Data(json.utf8)).person
print(person) // "Person(name: "Mike", hobby: "fishing")\n"
} catch {
print(error)
}