Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 428
Andre Valdivia Avatar asked Oct 28 '25 14:10

Andre Valdivia


1 Answers

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.

like image 68
Cristik Avatar answered Oct 31 '25 05:10

Cristik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!