0

springboot(22)fastjson设置不序列化字节流

 2 years ago
source link: https://wakzz.cn/2018/08/21/springboot/(22)fastjson%E8%AE%BE%E7%BD%AE%E4%B8%8D%E5%BA%8F%E5%88%97%E5%8C%96%E5%AD%97%E8%8A%82%E6%B5%81/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

springboot(22)fastjson设置不序列化字节流

祈雨的博客
2018-08-21

当设置fastjson为springboot的全局序列化工具后,当controller返回二进制字节流时,字节流被fastjson序列化为字符串了。

@RequestMapping(value = "/downloadInfo.json")
public ResponseEntity<byte[]> xx(){
return xx;
}
  • Preview

image

  • Response

image

fastjson默认的MediaType支持为全部,因此需要指定fastjson支持的MediaType。对于fastjson不支持的application/octet-stream使用ByteArrayHttpMessageConverter直接发送到前端。

@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XML);
supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
supportedMediaTypes.add(MediaType.TEXT_XML);
fastConverter.setSupportedMediaTypes(supportedMediaTypes);

HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter,new ByteArrayHttpMessageConverter());
}

并controller层指定MediaType类型

@RequestMapping(value = "/downloadInfo.json")
public ResponseEntity<byte[]> xx(){
HttpHeaders headers = new HttpHeaders();
headers.setContentLength(buffer.length);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<>(buffer, headers, HttpStatus.OK);
}
  • Preview

image

  • Response

image


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK