为了账号安全,请及时绑定邮箱和手机立即绑定

JSON无效的UTF-8中间字节

JSON无效的UTF-8中间字节

JSON无效的UTF-8中间字节当(Jackson,本例)JSON引擎尝试解析一些未以UTF-8编码的JSON时,会发生此错误。如何告诉引擎它应该期望与UTF-8不同的东西,例如UTF-16?HttpHeaders requestHeaders = createSomeHeader();RestTemplate restTemplate = new RestTemplate();HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);String url = "someurl"ResponseEntity<MyObject[]> arrayResponseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, MyObject[].class);错误日志:Caused by: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Invalid UTF-8 middle byte 0x20at [Source: org.apache.http.conn.EofSensorInputStream@44d397b0; line: 92, column: 42]; nested exception is org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x20at [Source: org.apache.http.conn.EofSensorInputStream@44d397b0; line: 92, column: 42]at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:138)at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:74)at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:622)
查看完整描述

3 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

我在Java客户端应用程序中得到了这个异常,我正在序列化这样的JSON

String json = mapper.writeValueAsString(contentBean);

在服务器端,我使用Spring Boot作为REST端点。例外是:

嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:无效的UTF-8起始字节0xaa

我的问题是,我没有在HTTP客户端上设置正确的编码。这解决了我的问题:

updateRequest.setHeader("Content-Type", "application/json;charset=UTF-8");StringEntity entity= new StringEntity(json, "UTF-8");updateRequest.setEntity(entity);

Android设置内容类型为HttpPost


查看完整回答
反对 回复 2019-08-28
?
繁星coding

TA贡献1797条经验 获得超4个赞

我在不同平台之间不一致地遇到了这个问题,因为我从Mapper获得了JSON作为String并自己完成了写作。有时它作为ansi进入文件,其他时候正确地作为UTF8。我切换到了

mapper.writeValue(file, data);

让Mapper执行文件操作,它开始正常工作。


查看完整回答
反对 回复 2019-08-28
  • 3 回答
  • 0 关注
  • 6941 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信