gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:14:27 25 4
gpt4 key购买 nike

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

最佳答案

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

添加 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);

关于json - 如何避免在 resttemplate postForObject 中进行字符串转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52445749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com