2

Using koltinx.serialization, is there a way to enable the "value" serializer to take it's ID from the "key" of the map entry?

For example, given the following JSON:

{
  "data": {
    "key1": { "name": "value1" },
    "key2": { "name": "value2" },
  }
}

And the serializable data class:

@Serializable
data class DataEntry(val id: String, val name: String)

How can I write a KSerializer for the map (or for the map "value") that will enable the DataEntry serializer to take the value of it's id field from the map "key"?

The result being a List (or Map) of:

DataEntry("key1", "value1"),
DataEntry("key2", "value2"),

I know that I can deserialise the map using DataEntry(val name: String) (without id) and then build a list of entries with id's from that. But in my case, for the map "value" I actually have many large data types, and this would require duplicating a lot of code. I want a generic way to handle this scenario given any data type.

Edric
  • 24,639
  • 13
  • 81
  • 91
Brett
  • 298
  • 2
  • 16
  • 1
    I would suggest writing another data class that truly represent the json format, then write converter methods between the two, rather than trying to perform complicated magic. – Ricky Mo Sep 26 '22 at 04:39
  • Yeah that is what I'm doing for now, but this question is "how to do the magic", because I as mentioned I have many large data types and want to avoid duplicating all the data classes. – Brett Sep 26 '22 at 08:19
  • What about this: 1. Create a `interface HasJsonKey { val key: String }`, 2. Implement the interfaces in your DTOs, 3. Create a util function that will convert a list of `HasJsonKey`s to a suitable `Map`. The downside is that key would be duplicated in the body. – aSemy Sep 29 '22 at 05:48

0 Answers0