Say I have the following code:
import Foundation
let jsonData = """
[
{"firstname": "Tom", "lastname": "Smith", "age": {"realage": "28"}},
{"firstname": "Bob", "lastname": "Smith", "age": {"fakeage": "31"}}
]
""".data(using: .utf8)!
struct Person: Codable {
let firstName, lastName: String
let age: String?
enum CodingKeys : String, CodingKey {
case firstName = "firstname"
case lastName = "lastname"
case age
}
}
let decoded = try JSONDecoder().decode([Person].self, from: jsonData)
print(decoded)
Everything is working except age
is always nil
. Which makes sense. My question is how can I set the Person's age = realage
or 28
in the first example, and nil
in the second example. Instead of age
being nil
in both cases I want it to be 28
in the first case.
Is there a way to achieve this only using CodingKeys
and not having to add another struct or class? If not how can I use another struct or class to achieve what I want in the simplest way possible?
Encode and Decode Manually
andAdditionalInfoKeys
. But am getting an errorDesignated initializer cannot be declared in an extension of 'Person'; did you mean this to be a convenience initializer?
andInitializer requirement 'init(from:)' can only be satisfied by a 'required' initializer in the definition of non-final class 'Person'
– Flashing