https://kotlinlang.org logo
Title
r

Ryan Brink

04/09/2023, 5:14 PM
How would one go about using kotlinx to serialize what is essentially a union type? For example, the swagger 2.0 spec allows for many types of objects to be specified, and most conform quite nicely to kotlinx polymorphic serialization, providing a 'type' key to hint at the payload structure. However, almost all of these fields could also be a
$ref
payload, which is a simple single value data class with that one parameter. short snippet example
BlkioWeightDevice:
        description: |
          Block IO weight (relative device weight) in the form:
[{"Path": "device_path", "Weight": weight}]
type: "array"
        items:
          type: "object"
          properties:
            Path:
              type: "string"
            Weight:
              type: "integer"
              minimum: 0
      BlkioDeviceReadBps:
        description: |
          Limit read rate (bytes per second) from a device, in the form:
[{"Path": "device_path", "Rate": rate}]
type: "array"
        items:
          $ref: "#/definitions/ThrottleDevice"
b

Ben Woodworth

04/09/2023, 5:27 PM
Have you looked into the
JsonContentPolymorphicSerializer
, which lets you manually determine the type to deserialize as from the shape of the JSON, instead of having an object with a type field?
r

Ryan Brink

04/09/2023, 5:37 PM
That looks very promising, thank you!