Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
155 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...