EyalR
EyalR

Reputation: 31

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 the Json I am getting a LinkedHashmap in the T and the de-sirializtion is to the base object Animal.

When I am adding restriction to the T i.e. than it works perfectly because of the Jackson annotations

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

But that is not the behavior that I wanted - I don't use < X extends Y >.

Is there a way to work with java generics and get the right object that was serialized?
Is there a way to accomplish it without annotations?

Upvotes: 3

Views: 781

Answers (1)

Erik Gillespie
Erik Gillespie

Reputation: 3959

You can specify a TypeReference when reading the value from your ObjectMapper in order to parse the correctly typed object:

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

Upvotes: 2

Related Questions