前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot 2.0 + FastJson 1.2.+作为JSON序列化

Spring Boot 2.0 + FastJson 1.2.+作为JSON序列化

作者头像
干货满满张哈希
发布2021-04-12 14:12:39
9590
发布2021-04-12 14:12:39
举报
文章被收录于专栏:干货满满张哈希

SpringBoot配置FastJson的时候,报错:

代码语言:javascript
复制
java.lang.IllegalArgumentException: Content-Type cannot contain wildcard type '*'
	at org.springframework.util.Assert.isTrue(Assert.java:116) ~[spring-core-5.0.13.RELEASE.jar!/:5.0.13.RELEASE]
	at org.springframework.http.HttpHeaders.setContentType(HttpHeaders.java:861) ~[spring-web-5.0.13.RELEASE.jar!/:5.0.13.RELEASE]
	at org.springframework.http.converter.AbstractHttpMessageConverter.addDefaultHeaders(AbstractHttpMessageConverter.java:255) ~[spring-web-5.0.13.RELEASE.jar!/:5.0.13.RELEASE]
	at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:210) ~[spring-web-5.0.13.RELEASE.jar!/:5.0.13.RELEASE]
	at com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter.write(FastJsonHttpMessageConverter.java:244) ~[fastjson-1.2.57.jar!/:?]

看FastJson初始化:

代码语言:javascript
复制
public static final MediaType ALL = valueOf("*/*");
public FastJsonHttpMessageConverter() {
    super(MediaType.ALL);  // */*
}

看来不能有通配符,所以需要像下面配置:

代码语言:javascript
复制
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
    //创建FastJson信息转换对象
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter =
            new FastJsonHttpMessageConverter();

    List supportedMediaTypes = Lists.newArrayList();
    //从1.1.41升级到1.2.之后的版本必须配置,否则会报错
    supportedMediaTypes.add(MediaType.APPLICATION_JSON);
    supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);

    //创建FastJson对象并设定序列化规则
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    //添加自定义valueFilter
    //规则赋予转换对象
    fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
    StringHttpMessageConverter stringHttpMessageConverter =
            new StringHttpMessageConverter(Charset.defaultCharset());

    fastJsonConfig.setSerializerFeatures(
            //消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
            SerializerFeature.DisableCircularReferenceDetect,
            //是否输出值为null的字段,默认为false
            SerializerFeature.WriteMapNullValue
    );

    return new HttpMessageConverters(fastJsonHttpMessageConverter, stringHttpMessageConverter);
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/06/14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档