gpt4 book ai didi

java - 将列表序列化为 json 时出现异常

转载 作者:行者123 更新时间:2023-11-30 06:28:59 35 4
gpt4 key购买 nike

我在将对象列表序列化为 JSON (Jackson) 时遇到问题。我的对象包含带有德语变音符号的字符串(例如 ä、ö、ü、ß)。当我将包含这些对象的列表发送到服务器时,我收到一个 JsonMappingException: Invalid UTF-8 middle byte。我 100% 问题出在客户端,因为当我通过 postman 发送 JSON 字符串时,它工作得很好。

public static ResponseEntity<?> exchange(String servicePath, HttpMethod method, Class returnClass, List<? extends BaseObject> objectList, Object... uriVariableValues) throws JsonProcessingException, UnsupportedEncodingException
{
RestTemplate template = new RestTemplate();
template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
template.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));

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

String url = ConfigHandler.getServicePath(servicePath);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(ConfigHandler.getStringProperty("baseUrl"));
URI uri = builder.path(url).buildAndExpand(uriVariableValues).toUri();
byte[] bytes = Utils.getJacksonObjectMapper().writeValueAsBytes(objectList);

//String urlParameters = new String(Utils.getJacksonObjectMapper().writeValueAsString(objectList).getBytes("UTF-8"));
String urlParameters = new String(bytes, "UTF-8");
//urlParameters = urlParameters.replaceAll("ß", "HURZ");
System.out.println("WebUtils.exchange - JSON: "+urlParameters);

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

return template.exchange(uri, method, entity, returnClass);
}

public static ObjectMapper getJacksonObjectMapper()
{
ObjectMapper mapper = new ObjectMapper()
.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module()).registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

return mapper;
}

相关 JSON 字符串如下 {"objectType":"TRANSLATION_PARAMETER","changed":true,"type":"java.lang.String","locale":"de_DE","value":"Schließen","section":null,"prettyId":"","active":true,"createdDate":"2017-10-01T13:35:52.6","name":"General.close","id":0,"description":" "}

最佳答案

如果将来有人偶然发现这个问题,解决方案是在 HttpHeaders 中添加更多内容:

HttpHeaders headers = new HttpHeaders();
MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
headers.setContentType(mediaType);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setAcceptCharset(Arrays.asList(Charset.forName("UTF-8")));

关于java - 将列表序列化为 json 时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46513146/

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