Search code examples
javaserializationresttemplate

How to deserialize nested list with RestTemplate?


I have a response which was get from calling RestTemplate. I have a problem in deserializing the response to the target class. I can get "code" and "message", but I can not get data as a list. Here is the my response class and RestTemplate call.

public class DataResponse {
    Long code;
    String message;
    BusinessClusterData data;
    public class BusinessClusterData {
        @SerializedName("data")
        List<BusinessClusterContent> businessClusterContentList;
        Long count;
    }
}
ResponseEntity<DataResponse> response = 
        restTemplate.exchange(url, HttpMethod.GET, entity, DataResponse.class);

Here is the response.

{
    "code": 0,
    "message": "ok",
    "data": {
        "data": [
        {
            "name": "test_name",
            "host": "test_host",
            "segInfo": [
            {
                "state": "applyed",
                "formId": 42158
            }
        ]}
      ],
    "count": 1
  }
}

Solution

  • You should use @JsonProperty (com.fasterxml.jackson.annotation.JsonProperty) instead of Gson's @SerializedName like

    public class BusinessClusterData {
        @JsonProperty("data")
        List<BusinessClusterContent> businessClusterContentList;
        Long count;
    }
    

    Also i think you should make BusinessClusterData a static class, since it's not dependent on an instance of the DataResponse