Expected this: name
-> fullname
struct Person: Codable {
let name: String
enum CodingKeys: String, CodingKey {
case name = "fullname"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
}
}
let jsonString = """
{
"name": "John"
}
"""
let jsonDecoder = JSONDecoder()
if let jsonData = jsonString.data(using: .utf8),
let decodedPerson = try? jsonDecoder.decode(Person.self, from: jsonData) {
print(decodedPerson.name) // Output: "John"
}
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
if let encodedData = try? jsonEncoder.encode(decodedPerson),
let encodedString = String(data: encodedData, encoding: .utf8) {
print(encodedString)
}
But the reality that second output produce this:
{
"name" : "John"
}