问题
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