Search code examples
javajsonspring-bootjacksonresttemplate

RestTemplate Map JSON array to list of objects


I'm having trouble mapping the environments LetakTandaTanganResponseDto in the below JSON response output into a list of LetakTandaTanganResponseDto objects using RestTemplate. I have a response from URL which looks like:

{
  "code": "00",
  "desc": "SUCCESS",
  "body": [
    {
      "id": 71,
      "createdate": null,
      "lx": "104",
      "ly": "632",
      "page": 1,
      "prfKe": 0,
      "rx": "260",
      "ry": "632",
      "ttdKe": 1,
      "formatItemId": null,
      "formatPdfId": 10
    },
    {
      "id": 72,
      "createdate": null,
      "lx": "485",
      "ly": "629",
      "page": 1,
      "prfKe": 0,
      "rx": "692",
      "ry": "629",
      "ttdKe": 2,
      "formatItemId": null,
      "formatPdfId": 10
    },
    {
      "id": 73,
      "createdate": null,
      "lx": "585",
      "ly": "729",
      "page": 1,
      "prfKe": 0,
      "rx": "792",
      "ry": "729",
      "ttdKe": 3,
      "formatItemId": null,
      "formatPdfId": 10
    }
  ]
}

RestTemplate code.

ResponseEntity<List<LetakTandaTanganResponseDto>> letakTTDResponse = restTemplate.exchange(uri, HttpMethod.GET, entity, new ParameterizedTypeReference<List<LetakTandaTanganResponseDto>>() {
                });
                if (letakTTDResponse != null && letakTTDResponse.hasBody()) {
                    listletakTTD = letakTTDResponse.getBody();
                }
  return listletakTTD;

Where as, if I happen to use a custom Value object, somethings like:

@Data
@ToString
public class LetakTandaTanganResponseDto {

    public String code;
    public String desc;
    public Body body;

    @Data
    @ToString
    public class Body {

        public Long id;
        public Integer ttd_ke;
        public Integer page;
        public String lx;
        public String ly;
        public String rx;
        public String ry;
        public String createdate;
        public Integer prfKe;
        public Long formatItemId;
        public Long formatPdfId ;
    }
}

Can you help how to the JSON list structure mentioned above can be mapped to an object?


Solution

  • Try changing your response class as per the json response

    public class LetakTandaTanganResponseDto {
        public String code;
        public String desc;
        public List<Body> body;
        // ...
    }
    

    and your response would be

    ResponseEntity<LetakTandaTanganResponseDto> letakTTDResponse = restTemplate.exchange(uri, HttpMethod.GET, entity, new ParameterizedTypeReference<LetakTandaTanganResponseDto>() {
               });
                if (letakTTDResponse != null && letakTTDResponse.hasBody()) {
                    listletakTTD.setBody( letakTTDResponse.getBody());
                }
      return listletakTTD;