Kotlinx.serialization: Polymorphism support

Created on 18 Feb 2019  路  3Comments  路  Source: Kotlin/kotlinx.serialization

sealed class Shape
class Circle(val radius: Double) : Shape
class Rectangle(val width: Double) : Shape

There are 2 types of polymorphism:

  1. Polymorphism by field value, aka discriminator
    1.1 Discriminator embedded in object
[ { "type": "CIRCLE", "radius": 10.0 }, { "type": "RECTANGLE", "width": 20.0 } ]

1.2 Discriminator external

[ { "type": "CIRCLE", "data": { "radius": 10.0 } }, { "type": "RECTANGLE", "data": { "width": 20.0 } } ]
  1. Polymorphism by field name, aka union, or anyOf from Swagger
[ { "radius": 10.0 }, { "width": 20.0 } ]

Because only Circle class has radius field, first object from list will be deserialized in Circle class.

Also should be possible to do nested deserialization(multi level).

Please add support for all this cases.

feature

Most helpful comment

I doubt that we want to implement 2) because it is quite unhandy to determine type from a set of fields. It also can be emulated with external serializer which reads JSON AST first, so no special support of format is required.

For 1), we have #346 and we will try to do our best and include it in the next release.

All 3 comments

I doubt that we want to implement 2) because it is quite unhandy to determine type from a set of fields. It also can be emulated with external serializer which reads JSON AST first, so no special support of format is required.

For 1), we have #346 and we will try to do our best and include it in the next release.

For 2 we need first to determinate all the children of a parent class, then for every child class should be determinate what fields are unique(and required) per class. So on deserialization should be checked if an object contains that unique fields. You can see that as 1.1 but with multiple discriminators.

Thanks for 1 point.

With #421 and #394 included in 0.11.0, I think most of the popular cases are covered by now and I can close this.

Was this page helpful?
0 / 5 - 0 ratings