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

爱⌒轻易说出口 提交于 2020-07-16 05:07:36

问题


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

    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:


If you can't fix your double encoded json you can provide your own custom decoder method to your PerfectFamily class but I recommend using a struct:


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


来源:https://stackoverflow.com/questions/47917525/how-can-i-decode-partially-double-serialized-json-string-using-codable-protoco

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!