https://kotlinlang.org logo
#jackson-kotlin
Title
# jackson-kotlin
r

Rodrigo Silva

06/16/2020, 7:18 PM
Hello all. I'm using the lib, 
jackson-module-kotlin,
 to serialize but I'm having an error:
I have the following methods, to serilize to JsonNode and deserialize.
Deserializing a class:
But I always get the following error:
Copy code
java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class com.rjdesenvolvimento.aries.access.consumer.consumer.Consumer (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; com.rjdesenvolvimento.aries.access.consumer.consumer.Consumer is in unnamed module of loader 'app')
Could anyone help?
a

araqnid

06/16/2020, 7:27 PM
My guess is that you have to tell Jackson what the “T” type is when deserializing- if you don’t, it assumes “T” is “Any” and just uses the default serialization - which will convert a JSON object into a LinkedHashMap. Are you expecting an
Event<Consumer>
?
You tell it what type “T” is by passing a TypeReference - the Kotlin module has a helper function to create one called
jacksonTypeRef()
r

Rodrigo Silva

06/16/2020, 7:29 PM
Yes, I'm waiting for
Event <Consumer>
But I also expect other classes, like
Event <Person>
Event <Address>
.... How do I solve this problem?
one way to go about it is to serialize a "type" property that jackson can key off of when deserializing based on polymorphic type annotations
a

araqnid

06/16/2020, 7:32 PM
sth like
Copy code
jacksonObjectMapper().readValue("{}", jacksonTypeRef<Event<Consumer>>())
a

araqnid

06/16/2020, 7:32 PM
yes, the polymorphic deserialisation works too, provided the JSON has a clear indication which type is there
if that type is more from context, it might be easier to specify the type when reading
j

Joe

06/16/2020, 7:35 PM
agreed, if you know what you're going to get then Steve's way is easier to understand what's going on, if you're listening for messages and don't know the order they'll arrive in, then the JSON needs some way to tell which type is being read
r

Rodrigo Silva

06/16/2020, 7:37 PM
Thank you @araqnid, @Joe. I will read about it and try to implement it.
5 Views