I have an API reponse which contains a list of objects, each of which can be of a different type. These are defined as Data Classes:
@Schema(type = "object", title = "Activity", subTypes = (Run::class, Swim::class), discriminatorProperty = "objectType") interface Activity; @Schema(title = "Run") data class Run(val distance: Int, val type: String = "Run") : Activity @Schema(title = "Swim") data class Swim(val river: String, val type: String = "Swim") : Activity
I will eventually have a large number of these, maybe 50, so I want to find a lower-boilerplate, easy-maintenance solution.
I’m stuck in a circular problem:
- I can’t seem to use the type discriminator without including a type name in each object.
- I can include the type name in every object’s constructor as a default, but it’s not safe because it could be changed when the object is constructed.
- But if I make the field somehow un-settable, then I can’t construct the object based on an API request.
Is it possible to add these automatically? I asssume I could do something custom with Jackson annotations but my situation seems pretty mainstream. Did I miss something?
The fact that I have to mention each type name four times in the source file makes me think there’s a better solution.
I’m using Springdoc OpenAPI and OpenAPI spec 3.0.1