How to use Jackson with Generics

I have the following object structure:

public class Animal<T> implements IMakeSound<T>
public class Dog<T> extends Animal<T>
public class Cat<T> extends Animal<T>

I want to serialize and de-serialize my object using jackson.
The problem is that in Json I get a LinkedHashmap in T, and de-sirializtion to the underlying Animal object.

When I add a restriction on T ie, than it works great due to Jackson's annotations

@JsonSubTypes({
   @Type(value = PuffyTail.class, name = "puffyTail"),
   @Type(value = StraightTail.class, name = "straightTail") })
class Tail {
...

But this is not the behavior that I wanted - I do not use <X extends Y>.

Is there a way to work with java generics and get the desired object that has been serialized?
Is there a way to do this without annotations?

+3
source share
1 answer

TypeReference ObjectMapper :

Cat<PuffyTail> fluffyKitty = objectMapper.readValue(jsonString,
        new TypeReference<Cat<PuffyTail>>(){});
+2

All Articles