Spring restTemplate get raw json string

suraj bahl picture suraj bahl · Nov 3, 2017 · Viewed 30.8k times · Source

How can I get the raw json string from spring rest template? I have tried following code but it returns me json without quotes which causes other issues, how can i get the json as is.

ResponseEntity<Object> response  = restTemplate.getForEntity(url, Object.class);
String json = response.getBody().toString();

Answer

madhead picture madhead · Nov 3, 2017

You don't even need ResponseEntitys! Just use getForObject with a String.class like:

final RestTemplate restTemplate = new RestTemplate();
final String response = restTemplate.getForObject("https://httpbin.org/ip", String.class);

System.out.println(response);

It will print something like:

{
  "origin": "1.2.3.4"
}