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

How can I decode partially double serialized json string using `Codable` protocol?

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

如果您无法修复双重编码 json 您可以为您的 PerfectFamily 提供您自己的自定义解码器方法 class 但我建议使用结构:


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