Hi, looking for some guides how can I serialize a ...
# serialization
r
Hi, looking for some guides how can I serialize a field that can be a single JSON object or an array of JSON objects. The backend accepts either this:
Copy code
A single object needs to be sent as a JSON object
{
  "some_string": "blah",
  "some_long": 1234,
  "my_object": {
    "name": "Object 1",
    "value": "Object 1 value"
  }
}
or this:
Copy code
Multiple objects need to be sent as a JSON array of those objects
{
  "some_string": "blah",
  "some_long": 1234,
  "my_object": [
    {
      "name": "Object 1",
      "value": "Object 1 value"
    },
    {
      "name": "Object 2",
      "value": "Object 2 value"
    }
  ]
}
How can I achieve this? I don't want to duplicate the classes like
SingleObjectPayload
and
MultipleObjectsPayload
as there are many more params in it and I don't want to duplicate them.
1
e
if the backend accepts either, the client should be able to always send them as an array of objects
r
okay maybe I phrased that wrong, I also send a value with the type of my payload, so if the type is, let's say "single" then I need to send a json object, if it is a "multiple" then I need to send it as an array
can't send an array with a "single" type value
e
Copy code
@Serializable
sealed interface Base

@Serializable
class Single(val name: String, val value: String) : Base

@Serializable(with = MultipleSerializer::class)
class Multiple(val list: List<Single>) : Base, List<Single> by list

object MultipleSerializer : KSerializer<Multiple> {
  private val delegate = ListSerializer(Single.serializer())
  override val descriptor = delegate.descriptor
  override fun serialize(encoder: Encoder, value: Multiple) = delegate.serialize(encoder, value.list)
  override fun deserialize(decoder: Decoder): Multiple = Multiple(delegate.deserialize(decoder))
}
r
Works exactly the way I needed it to work. Thank you! 🙇
K 1
🙏🏾 1