Search code examples
jsonspringresttemplate

How to avoid string escape in resttemplate postForObject


Having a client should send plain json string to a RESTful service:

    ...
    final Gson gson = new GsonBuilder().create();
    final String payload = gson.toJson(data);

    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    final HttpEntity<String> entity = new HttpEntity<>(payload, headers);

    restTemplate.postForObject("http://localhost:8080/data/bulk", entity, Void.class);
    ...

The produced json by GSON looks like:

{ "id" : { "poid" : "5b70cabhsdf66d99sdakfj37e45" } ... }

The REST service now is receiving the request:

@RequestMapping(value = "/data/bulk", method = RequestMethod.POST)
public ResponseEntity<Void> bulkInbound(@RequestBody final String bulkjson) {

But the string in request body which should be exactly the same as the produced json looks like:

{ \"id\" : { \"poid\" : \"5b70cabhsdf66d99sdakfj37e45\" } ... }

So the string in the body is escaped which makes some problems. Sending the same json string via POSTMAN ist works like a charme without escaping. How can i tell resttemplate in my client not to escape my string?


Solution

  • So, after spending much time on research i think it is the best way to use JSONObject for that. My solution looks like:

    ...
    final JSONObject jsonobject = new JSONObject(data);
    
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    
    final HttpEntity<String> entity = new HttpEntity<>(jsonobject.toString(), headers);
    
    restTemplate.postForObject("http://localhost:8080/data/bulk", entity, Void.class);
    ...
    

    This works for me and solves my problem with String escaping.