Why #Codable# not working in below code?

╄→гoц情女王★ 提交于 2019-12-25 18:45:59

问题


I have below code to test Codable protocol and JSONDecoder.

import UIKit

class ClassA: Codable {
    var age: Int = 1
}

class ClassB: Codable {
    var ageInfo: ClassA?
    var name: String
}

let json4 = """
{
    "ageInfo": {},
    "name": "Jack"
}
""".data(using: .utf8)!

do {
    let d = try JSONDecoder().decode(ClassB.self, from: json4)
} catch let err {
    print(err)
}

My question is, why json4 can't be decode? or how I can decode json4?


回答1:


age in ClassA is declared non-optional so the key is required however in the JSON ageInfo is empty.

The error is

No value associated with key CodingKeys(stringValue: "age")

Either declare age as optional

var age: Int?

or insert the key-value pair in the JSON

{
    "ageInfo": {"age" : 1},
    "name": "Jack"
}



回答2:


Your ClassB has this:

var ageInfo: ClassA?

But that doesn’t help you with this JSON:

"ageInfo": {}

The problem is that ageInfo is present but it is also an empty dictionary. So there is a ClassA but it doesn't correspond to your definition of ClassA!

Change

class ClassA: Codable {
    var age: Int = 1
}

to

class ClassA: Codable {
    var age: Int? = 1
}


来源:https://stackoverflow.com/questions/51211597/why-codable-not-working-in-below-code

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