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

问题描述 投票:1回答:1

如何使用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)
    }
swift swift4 codable
1个回答
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)
}
© www.soinside.com 2019 - 2024. All rights reserved.