Search code examples
springspring-bootpostmanresttemplatepretty-print

How to get pretty formatted output from RestTemplate?


Below is my response from one of the server call from my Spring Boot app,

String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();

Then I am returning to client like,

return ResponseEntity.ok().body(result);

In postman I see json is printed with many \" rather pretty formated.

Is there I need to change in response side to see pretty formatted output in Postman?

Sample Postman output:

"{\"records\":[{\"pkg_name\":\"com.company.app\",\"start_time\":1580307656040,\"update_time\":12345,\"min\":0.0,\"create_time\":1580307714254,\"time_offset\":21600000,\"datauuid\":\"xyz\",\"max\":0.0,\"heart_beat_count\":1,\"end_time\":1580307656040,\"heart_rate\":91.0,\"deviceuuid\":\"abc\"}]}" ...

Expected output: Pretty formatted without \"


Solution

  • It seems to me that String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody(); returns double encoded json string. to unescape and get normal json

     String unwrappedJSON = objectMapper.readValue(result, String.class);
     return ResponseEntity.ok().body(unwrappedJSON);
    

    EDIT

    if result is normal json and not double escaped than you can try:

    JsonNode result = restTemplate.exchange(url, HttpMethod.GET, entity, JsonNode.class).getBody();
    
    return ResponseEntity.ok().body(result);