I'm having problems trying to deserialize from json string into the correct object since I have to check 2 properties before deserialize to the correct class, i.e.:
{
"org": "Company1",
"event_type": "REGISTER",
"day": "2021-01-01",
"data": {
"name": "Kyore",
"age": 10
}
},
{
"org": "Company2",
"event_type": "REGISTER",
"day": "2021-01-01",
"data": {
"name": "Casky",
"age": 12,
"lastName": "Kyky"
}
},
{
"org": "Company2",
"event_type": "DELETE",
"day": "2021-01-01",
"data": {
"id": "1234-1234-1234",
"reason": "user requested"
}
}
I could make it work with the basic polymorphic deserialization using the JsonTypes as you can see here
The problem now is that I have this "org" field that might give me the same "event_type" value, but with a different data, so I need to find a way to first check if org
is either Company1 or Company2 to call the correct JsonSubType, ie:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "org_id", include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
@JsonSubTypes(value = [
JsonSubTypes.Type(Company1Data::class, name = "Company1"),
JsonSubTypes.Type(Company2Data::class, name = "Company2")
])
abstract class EventData {
abstract fun validate()
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "event_type", include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
@JsonSubTypes(value = [
JsonSubTypes.Type(Cmp1RegisterData::class, name = "REGISTER")
])
abstract class Company1Data
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "event_type", include = JsonTypeInfo.As.EXTERNAL_PROPERTY)
@JsonSubTypes(value = [
JsonSubTypes.Type(Cmp2RegisterData::class, name = "REGISTER"),
JsonSubTypes.Type(DeleteData::class, name = "DELETE")
])
abstract class Company2Data
data class Cmp1RegisterData(
val name: String,
val age: Int
) :Company1Data()
data class Cmp2RegisterData(
val name: String,
val age: Int,
val lastName: String
) :Company2Data()
data class DeleteData(
val id: String,
val reason: String
) :Company2Data()
The above code does not work since both CompanyData
are abstract, so they can not be initialized, and using class won't work since I have the validate
function in the "main" abstract class and I want to override it in the last class I'm deserializing (i.e.: Cmp2RegisterData)