Home > Back-end >  Spring boot: Converting response to pojo
Spring boot: Converting response to pojo

Time:03-17

I am busy with an integration test. I have a struggle with converting the response body to the required entity data:

  HttpHeaders headers = new HttpHeaders();
        headers.add("header_name", "header_value");
        headers.setContentType(MediaType.APPLICATION_XML);
        HttpEntity<String> request = new HttpEntity<String>(fileToBeRead("file.xml"), headers);
        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8081/api", request, String.class);

how can I convert the the received json data to Java POJO.?

CodePudding user response:

Simply use your POJO instead of String.class in the "post" method:
ResponseEntity<MyPojo> response = restTemplate.postForEntity("http://localhost:8081/api", request, MyPojo.class);

or directly:
MyPojo myPojo = restTemplate.postForObject("http://localhost:8081/api", request, MyPojo.class);

If you have followed the standard Spring Boot setup for your tests, then the Resttemplate is automatically configured with sane defaults to deserialize your POJO (using the Jackson library most likely).

  • Related