如何使用`Codable`协议解码部分双序列化的json字符串?

时间:2017-12-21 03:31:47

标签: swift swift4 codable

如何使用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)
    }

1 个答案:

答案 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)
}