3

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?

Filburt
  • 17,626
  • 12
  • 64
  • 115
EyalR
  • 31
  • 1

1 Answers1

2

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>>(){});
Erik Gillespie
  • 3,929
  • 2
  • 31
  • 48