【Springboot学习 | 3】配置使用FastJson返回Json视图

一、添加依赖

fastJson为阿里巴巴2017年开始发布并维护,目的是将fastJson加入到SpringBoot等项目内,配置json返回视图使用fastJson解析。

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.59</version>
        </dependency>

二、添加FastJson配置

在前面一文的基础上:【springboot学习 | 2】jpa+mysql8.0增删改查
创建一个FastJsonConfiguration配置信息类,与Application同级:
在这里插入图片描述
配置类解释:

  1. @Configuration:让SpringBoot自动加载类内的配置
  2. 继承了WebMvcConfigurationSupport是SpringBoot内部提供专门处理用户自行添加的配置,里面不仅仅包含了修改视图的过滤还有其他很多的方法,包括后面可能会用到的拦截器,过滤器,Cors配置等.
  3. configureMessageConverters():修改自定义消息转换器
  4. SerializerFeature:过滤
    • DisableCircularReferenceDetect,//消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
    • WriteMapNullValue//是否输出值为null的字段,默认为false。

测试版本:
FastJsonConfiguration.java

package com.springboot.three;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;


@Configuration
public class FastJsonConfiguration extends WebMvcConfigurationSupport {
    /**
     * 修改自定义消息转换器
     * @param converters 消息转换器列表
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
    {
        //调用父类配置
        super.configureMessageConverters(converters);
        //创建消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //创建配置类
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //返回内容的过滤
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue//,
                //SerializerFeature.WriteNullStringAsEmpty
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //将fastjson添加到视图消息转换器列表内
        converters.add(fastConverter);
    }
}

三、测试

将数据库设置一个值为空:
在这里插入图片描述
浏览器查询:http://127.0.0.1:8080/user/list ,测试结果:
在这里插入图片描述
修改FastJson配置代码:
在这里插入图片描述
再运行Springboot主函数,浏览器测试:
在这里插入图片描述

补充

问题描述
今天在用postman进行测试时,控制台报出以下错误:
java.lang.IllegalArgumentException: Content-Type cannot contain wildcard type '*'

原因分析:
升级到最新版本的fastjson以后报的错,发现fastjson从1.1.41升级到1.2.59之后,请求报错:
json java.lang.IllegalArgumentException: ‘Content-Type’ cannot contain wildcard type ‘*’

原因是在1.1.41中,FastJsonHttpMessageConverter初始化时,设置了MediaType。

public FastJsonHttpMessageConverter(){
    super(new MediaType("application", "json", UTF8), new MediaType("application", "*+json", UTF8));
}

而在1.2.59中,设置的MediaType为‘/’,即:

public FastJsonHttpMessageConverter() {
    super(MediaType.ALL);  // */*
}

后续在org.springframework.http.converter.AbstractHttpMessageConverter.write过程中,又要判断Content-Type不能含有通配符,这应该是一种保护机制,并强制用户自己配置MediaType。

参考:Spring Boot配置FastJson报错’Content-Type’ cannot contain wildcard type ‘*’

解决办法

完整的FastJsonConfiguration:

package com.springboot.three;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.ArrayList;
import java.util.List;


@Configuration//@Configuration让SpringBoot自动加载类内的配置
//WebMvcConfigurationSupport是SpringBoot内部提供专门处理用户自行添加的配置,
// 里面不仅仅包含了修改视图的过滤还有其他很多的方法,包括后面可能会用到的拦截器,过滤器,Cors配置等.
public class FastJsonConfiguration extends WebMvcConfigurationSupport {
    /**
     * 修改自定义消息转换器
     * @param converters 消息转换器列表
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
    {
        //调用父类配置
        super.configureMessageConverters(converters);
        //创建消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        //升级最新版本需加=================================================
        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_OCTET_STREAM);
        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.IMAGE_GIF);
        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
        supportedMediaTypes.add(MediaType.IMAGE_PNG);
        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);

        //创建配置类
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //返回内容的过滤
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,//消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
                //SerializerFeature.WriteMapNullValue,//是否输出值为null的字段,默认为false。
                SerializerFeature.WriteNullStringAsEmpty//数据库字段设置了NULL时,前端返回json为""替代null
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //将fastjson添加到视图消息转换器列表内
        converters.add(fastConverter);
    }
}

postman测试:无误!
在这里插入图片描述

总结

json为空时,在前端调用会显示null效果不好,或者js语言报错,都是很不便的;
fastjson则可以避免这种情况。

?源码地址:
https://github.com/cungudafa/SpringBoot

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值