如何避免在 resttemplate postForObject 中进行字符串转义

How to avoid string escape in resttemplate postForObject

让客户端应该将纯 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 不要转义我的字符串?

因此,在花了很多时间进行研究之后,我认为这是为此使用 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);
...

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

对于仍然遇到这个问题的人......我花了几个小时才找到它:

添加 StringHttpMessageConverter 作为第一个转换器解决了转义问题,并且仍然使用 GSON 进行序列化(即 gson.toJson(data))。通过此更改,JSON 发布时带有未转义的双引号。

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(new StringHttpMessageConverter());
    converters.add(new GsonHttpMessageConverter());
    restTemplate.setMessageConverters(converters);