Spring restTemplate get raw json string
Asked Answered
A

2

40

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();
Adena answered 3/11, 2017 at 20:45 Comment(2)
can you put the example print out?Creolized
have you tried to use String? restTemplate.getForEntity(url, String.class);Brig
A
65

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"
}
Arleta answered 3/11, 2017 at 21:17 Comment(3)
My return type is object and I want the raw json string?Paterson
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-stringBravado
new implementations of Spring no longer work when contentType is application/json so you can use java.util.LinkedHashMap as response object and will convert Json to a mapPushy
G
0

You can also use restTemplate.execute and pass ResponseExtractor that just parses the InputStream from the body.

public <T> T execute(String url,
    org.springframework.http.HttpMethod method,
    org.springframework.web.client.RequestCallback requestCallback,
    org.springframework.web.client.ResponseExtractor<T> responseExtractor,
    Object... uriVariables )

For example:

String rawJson = restTemplate.execute(url, HttpMethod.GET, (clientHttpRequest) -> {}, this::responseExtractor, uriVariables);

// response extractor would be something like this
private String responseExtractor(ClientHttpResponse response) throws IOException {
    InputStream inputStream = response.getBody();
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    for (int length; (length = inputStream.read(buffer)) != -1; ) {
        result.write(buffer, 0, length);
    }
    return result.toString("UTF-8");
}

This also bypasses ObjectMapper if your using Jackson and stringify invalid JSON.

Gomer answered 16/7, 2023 at 0:30 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.