我有一个问题,将对象列表seralized为JSON(杰克逊)。我的对象包含带有德语变音符号的字符串(例如ä,ö,ü,ß)。当我将包含这些对象的列表发送到我的服务器时,我得到一个 JsonMappingException:无效的UTF-8中间字节。我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":" "}
答案 0 :(得分:1)
如果有人在将来偶然发现这个问题,那么解决方案就是向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")));
答案 1 :(得分:0)
在客户端设置正确的编码:
CLOB