0

Below is the class structure:

Response.java

@Getter
@Setter
public class Response implements Serializable{

  private final static long serialVersionUID = 8875657894025733696L;

  @JsonProperty ("status")
  public String status;

  @JsonProperty("payload")
  public Payload payload;
}

Payload.java

@Getter
@Setter
public class Payload<T> implements Serializable {

  private final static long serialVersionUID = 1732258949055126977L;

  @JsonProperty ("data")
  public List <T> data;
}

Here T is generic class

 Response response = restTemplate.postForObject(url, request, Response.class);

What could be JavaType or TypeReference to replace Response.class in the above statement, so that I can directly get a List of T by response.getPayload().getData();? Currently it is coming as LinkedHashMap.

David Walschots
  • 12,279
  • 5
  • 36
  • 59

1 Answers1

0

I think what you are asking about is whether you can determine (at runtime) the actual type of an object to be deserialized. Jackson allows you to do this, with some extra annotations. I was curious how this worked, and wrote a sample program a few years ago to test it out.

Note that there a few different options (see JacksonPolymorphicDeserialization for more details) and I've chosen to implement only one of them.

In my sample, I just annotated the parent class with the property to use to figure out which subclass is being deserialized, and which values map to each possible subclass:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Pet.class, name="pet"),
    @JsonSubTypes.Type(value = Child.class, name="child")
})
public abstract class Parent {...}
Adam Batkin
  • 51,711
  • 9
  • 123
  • 115