如何避免RestTemplate PostForObject中的字符串转义

时间:2018-09-21 14:22:14

标签: json spring resttemplate

拥有客户端应将纯json字符串发送到RESTful服务:

    ...
    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);
    ...

GSON产生的json如下:

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

REST服务现在正在接收请求:

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

但是请求正文中的字符串应与产生的json完全相同

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

因此,主体中的字符串被转义了,这带来了一些问题。 通过POSTMAN ist发送相同的json字符串的工作就像一个超级按钮而没有逃脱。 如何告诉客户端中的resttemplate不要转义我的字符串?

1 个答案:

答案 0 :(得分:0)

因此,在花费大量时间进行研究之后,我认为这是使用JSONObject的最佳方法。我的解决方案如下:

...
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);
...

这对我有用,并通过字符串转义解决了我的问题。

相关问题