Hi everyone. I’m trying to create a custom Seriali...
# serialization
i
Hi everyone. I’m trying to create a custom Serializer for the following class.
Copy code
class TreeNode(
    val value: MyData
) {
    val children = listOf<TreeNode>()
}
I’m trying to have the
value
field named dynamically based on its type (many classes inherit from
MyData
). Something like:
Copy code
{
   "data_one":{
      ...
   },
   "children":[
      {
         "data_two":{
            ...
         },
         "children":[
            {
               "data_three":{
                  ...
               },
               "children":[
                  
               ]
            },
            {
               "data_one":{
                  ...
               },
               "children":[
                  
               ]
            }
         ]
      }
   ]
}
How do I define the
SerialDescriptor
element that represents the collection of its own type? Right now, I have:
Copy code
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TreeNode") {
        element<DataOne>("data_one")
        element<DataTwo>("data_two")
        element<DataThree>("data_three")
        element("children", listSerialDescriptor<TreeNode>()) // this crashes because I'm trying to use the descriptor I'm currently creating
    }
When I change the
listSerialDescriptor<TreeNode>()
to for example
listSerialDescriptor<String>()
it encodes it the way I want it to, but I'm getting errors when decoding. How do I approach this? Still new to the library I hope I was clear enough 🙇‍♂️ Thanks!
n
when you use a sealed class it will have a type specifier and all work magically and you can configure it to be using any key by setting
classDiscriminator
or you can use something like JsonTransformingSerializer to pick the right serializer basedo n the jsonElement you are getting
i was bored.. so i made hacked something that matches that structure together: https://gist.github.com/NikkyAI/f7a9d0deb64a346c0a691c16da250815
but.. sealed classes default behaviour would be prettier still
i
Wow! Thanks a lot. Much appreciated 🙇