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"
}
If your goal is to decode the
namekey and output thefullnamekey (which is really confusing and means your code can't decode the JSON that it generates) then you need to update theCodingKeysto:and you need to update the
encodemethod to use.fullnameinstead of.name.Then you can parse the original JSON with the
namekey and then generate new JSON with afullnamekey.Here's your code with some cleanup and the changes I suggest:
The output is:
Just to reiterate. This is a bad idea. Your
Personclass, with these changes, can't decode the JSON that it encodes. Are you really sure that is what you want?