Given the classes:
class ComplementApp: Codable{
    let name: String
    let idSpring: String
}
class MasterClass: Encodable{
    let complement: ComplementApp
    ///Other propierties
}
I want to get:
//Where "Some ID" is the value of complement.idSpring
{
   complement: "Some ID"
   //Plus the other properties
}
Not
{
   complement: {
      name: "Some Name",
      idSpring: "Some ID"
   }
   //Plus other properties
}
Which is the default. I know that I can do it throw encode function and CodingKeys in MasterClass, but I have like 20 other variables, and I should add 19 extra keys. Can I achieve this implementing CodingKeys in ComplementApp?
You can achieve this via a custom encode(to:) implementation:
class ComplementApp: Codable {
    let name: String
    let idSpring: String
    func encode(to coder: Encoder) throws {
        var container = coder.singleValueContainer()
        try container.encode(idSpring)
    }
}
Using singleValueContainer will result in your object being encoded as a single value instead of a JSON object. And you don't have to touch the outer class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With