I have a question related to Jackson and polymorph...
# announcements
j
I have a question related to Jackson and polymorphism: is there a way to deserialize a JSON string without specifying a type? Assuming I don't own this message (e.g., external API) and I have two separate messages that come in at separate times:
Copy code
{
    "responseCode": 200
    "responseMessage": "You did something successfully"
}

{
    "errorCode": 401
    "errorDescription": "Permission denied"
}
And I want to deserialize this message with some data classes that I created based on these messages through polymorphism (see abstract class in next code block):
Copy code
data class MyDataClass(
    val responseCode: Int,
    val responseMessage: String
): MyAbstractClass()

data class MyOtherDataClass(
    val errorCode: Int,
    val errorDescription: String
): MyAbstractClass()
And I am resolving these messages through a function that will use the Jackson Object Mapper to deserialize the stringified JSON payload:
Copy code
@JsonSubTypes(
    JsonSubTypes.Type(value = MyDataClass::class),
    JsonSubTypes.Type(value = MyOtherDataClass::class)
)
@JsonIgnoreProperties(ignoreProperties = true)
abstract class MyAbstractClass

fun receiveMessage(message: String) {
    val convertedMessage = jacksonObjectMapper().readValue<MyAbstractClass>(message)

    <http://log.info|log.info>(convertedMessage)
    /* prints either:
    MyDataClass(responseCode=200, responseMessage=You did something successfully)
    OR
    MyOtherDataClass(errorCode=401, errorDescription=Permission denied)
    */
}
But since I haven't described how to identify the data class (using
@JsonTypeInfo
), it fails. To repeat, I am curious if there is a way that I can deserialize the incoming message to one of my polymorphic types without having to specify the
@JsonTypeInfo
.