Search code examples
swiftencodable

encode class to single value not dictionary swift


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?


Solution

  • 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.