Spring restTemplate get raw json string

40,849

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"
}
Share:
40,849
suraj bahl
Author by

suraj bahl

Updated on November 04, 2020

Comments

  • suraj bahl
    suraj bahl over 3 years

    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();
    
  • Brooklyn99
    Brooklyn99 over 3 years
    My return type is object and I want the raw json string?
  • wutzebaer
    wutzebaer over 3 years
    this won't wotk when the server sends application/json as content type Cannot deserialize instance of java.lang.String out of START_ARRAY token it will only gibt you a string if the body just contains a json-string