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

后端 未结 1 447
南旧
南旧 2021-01-22 18:21

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

    class Person : Codable {
        var name : String?
        var         


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 18:41

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

    0 讨论(0)
提交回复
热议问题