sealed class Entity
data class Bacteria(val speciesName: String): Entity()
data class Disease(val diseaseId: Long): Entity()
enum class EntityType {
MY_Bacteria,
MY_Disease
}
data class MyRequestBody(
val entityType: EntityType,
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "entityType",
defaultImpl = NoClass::class,
visible = true
)
@JsonSubTypes(
JsonSubTypes.Type(value = Disease::class, name = "MY_Disease"),
JsonSubTypes.Type(value = Bacteria::class, name = "MY_Bacteria")
)
val entity: Entity? = null
)
Inbound requests are of the type MyRequestBody
e.g.
{
"entityType": "MY_Bacteria",
"entity": {
"speciesName": "E. Coli"
}
}
entity
can also be missing
{
"entityType": "MY_Disease"
}
I'd like to have polymorphism on the entity
field of MyRequestBody
. The type is given by the sibling field, entityType
, which can be "MY_Bacteria" or "MY_Disease" which map to the Bacteria
and Disease
classes respectively.
This solution does not seem to work. I keep on getting a 400 with message "Failed to read HTTP message" when entity
is missing from the request body (it's not using the default value of null).
entityType
set asMY_Disease
orMY_Bacteria
in your request ? can you post your request JSON ? – Jayesh Jun 23 '19 at 5:14include = JsonTypeInfo.As.PROPERTY
– Jayesh Jun 24 '19 at 18:01