Hi everyone, I'm working with an API that requires...
# serialization
r
Hi everyone, I'm working with an API that requires sending a JSON like this as payload
Copy code
{
  "draw": [
    {
      "dc": [
        28,
        4,
        3,
        "#FF0000"
      ]
    },
    {
      "dr": [
        20,
        4,
        4,
        4,
        "#0000FF"
      ]
    },
    {
      "dt": [
        0,
        0,
        "Hello",
        "#00FF00"
      ]
    }
  ]
}
where the
dc
,
dr
and
dt
can be in any order and amount inside the list, while their values are always the same amount and type (e.g.
Int
,
Int
,
Int
,
String
for
dc
and
Int
,
Int
,
String
,
String
for
dt
), but as a List. I'm trying to use Maps and Sealed classes but so far I didn't get anywhere. What would be the best and easiest way to generate this JSON with kotlinx.serialization? Btw, this is part of a way bigger JSON, but the rest of the JSON can be handled with a normal
data class
and some `List`s. Also, I only need to serialize it (send this as payload) and I do not have to deserialize it back, in case this could make things easier.
a
it sounds like you're looking for tuples https://github.com/Kotlin/kotlinx.serialization/issues/1906
if you're on JVM you can try ks3 - it has a helper function. See the test for an example https://github.com/Kantis/ks3/blob/v0.3.1/ks3-standard/src/jvmTest/kotlin/io/ks3/standard/TupleSerializerTest.kt
r
yeah I'm on JVM, I'll have a look thanks a lot for the hint 🙂
👍 1
I got pretty close but, since I'm using sealed classes, I get this annoying
type
inside the JSON:
Copy code
"draw":[
      {
         "dc":[
            "type":"io.ks3.Tuple(com.leinardi.kal.model.Draw.Circle)",
            28,
            4,
            3,
            "#FF0000"
         ]
      },
      {
         "dr":[
            "type":"io.ks3.Tuple(com.leinardi.kal.model.Draw.Rectangle)",
            20,
            4,
            4,
            4,
            "#0000FF"
         ]
      },
      {
         "dt":[
            "type":"io.ks3.Tuple(com.leinardi.kal.model.Draw.Text)",
            0,
            0,
            "Hello",
            "#00FF00"
         ]
      }
   ],
Does anyone know how could I get rid of it?
j
dc, dr and dt have always the same name?
r
j
I would do custom serializers for that with simple data classes and using json objects and json arrays as implementation detail. The usage would be really simple compared to get the same with maps and sealed classes
👍 1