处理返回结果中字段为空或为null,不展示字段的问题(字段展示不全)

418 阅读2分钟

这篇文章主要向大家介绍我在项目开发过程中遇到的问题----返回结果中字段为空或为null,不展示字段的问题(字段展示不全)

问题的相关描述:就是我在项目开发过程中遇到这样的问题在查询数据库中的数据的时候,在controller层将即将返回到前端的数据打印出来发现为空或者是为null的一些数据是是可以打印出这些字段的名字的,但是在就在我们讲这些数据返回到前端的时候我们就会发现我们之前打印出来的一些为null或者为空的数据字段在前段不显示出来了这是为什么?

这是因为我们在使用alibaba的fastjson格式化数据的时候他会默认将这些数据为null的过滤掉


解决办法

package com.aiqin.mgs.market.api.config; 
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
 
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
 
/**
 * description: fastjson处理返回的参数为null、或者不返回
 * version: 1.0
 * springboot 处理返回结果中字段为空或为null,不展示字段的问题(字段展示不全)
 */
@Configuration
public class FastJsonConfiguration extends WebMvcConfigurationSupport {
 
    /**
     * 使用阿里 fastjson 作为JSON MessageConverter
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                // 保留map空的字段
                SerializerFeature.WriteMapNullValue,
                // 将String类型的null转成""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将Number类型的null转成0
                SerializerFeature.WriteNullNumberAsZero,
                // 将List类型的null转成[]
                SerializerFeature.WriteNullListAsEmpty,
                // 将Boolean类型的null转成false
                SerializerFeature.WriteNullBooleanAsFalse,
                // 避免循环引用
                SerializerFeature.DisableCircularReferenceDetect);
 
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        List<MediaType> mediaTypeList = new ArrayList<>();
        // 解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypeList);
        converters.add(converter);
    }
}

这个配置类加入到SpringBoot的项目中就可以将上面的问题解决。后端返回为空或者为null的数据前段也能够拿到这些数据的字段。
SerializerFeature属性说明
QuoteFiledNames:输出key时是否使用双引号默认是true
WriteMapNullValue:输出值为null的字段,默认为false
WriteNullNumberAsZero:数值字段如果为null输出为0,而非null
WriteNullListAsEmpty: List字段如果为null,输出为[] ,而非null
WriteNullStringAsEmpty:字符类型字段如果为null,输出为"",而非null
WriteNullBolleanAsFalse:Boolean 字段如果为null,输出为false,而非null

[更多内容请看](使用JSON.toJSONString格式化成json字符串时保留null属性_java_脚本之家 (jb51.net))