-1

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?

matt
  • 515,959
  • 87
  • 875
  • 1,141
ZYiOS
  • 5,204
  • 3
  • 39
  • 45

2 Answers2

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"
}
vadian
  • 274,689
  • 30
  • 353
  • 361
1

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
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I see, so the default value of age is useless? I thought ```"ageInfo": {}``` is equal to ```"ageInfo": null```. – ZYiOS Jul 08 '18 at 02:30
  • That would only be if null and empty-dictionary were the same. They are not. “No dictionary at all” is not the same as “an empty dictionary.” – matt Jul 08 '18 at 04:07
  • Similarly in Swift itself, `nil` and `[:]` are two totally different things. – matt Jul 08 '18 at 21:29
  • Similarly in real life. “My cup is empty” is not the same as “I have no cup.” – matt Jul 08 '18 at 21:31