改变SpringBoot默认的HttpMessageCoverter

本文介绍了如何改变SpringBoot默认的HttpMessageConverter,避免在前后端数据转换时将NULL字段返回给前端,减轻前端开发的工作负担。通过引入fastjson依赖、配置转换器以及测试不同情况下的效果,展示了一种更干净的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

博主github
博主个人博客http://blog.healerjean.com

正常情况下我们SpringBoot为我们提供了HttpMessageCorverter用于前后台数据的转化,经常我们会发现返回到前台的对象,字段是NULL,这些NULL其实本不应该返回给前端显示,无疑是增加了前端小哥哥,小姐姐的负担

当然,你能想到的是使用@JsonInclude @JsonJgnore来解决,但是这里呢,使用的是另一个中解析的类

1、fastjson依赖

    <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.15</version>
    </dependency>

2、config

package com.hlj.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

import java.nio.charset.Charset;

@Configuration
public class HttpMessageConverterConfig {

    //引入Fastjson解析json,不使用默认的jackson
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        //1、定义一个convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        //2、添加fastjson的配置信息
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        SerializerFeature[] serializerFeatures = new SerializerFeature[]{
                //    输出key是包含双引号
                SerializerFeature.QuoteFieldNames,
                //    是否输出为null的字段,若为null 则显示该字段
//                SerializerFeature.WriteMapNullValue,
                //    数值字段如果为null,则输出为0
                SerializerFeature.WriteNullNumberAsZero,
                //     List字段如果为null,输出为[],而非null
                SerializerFeature.WriteNullListAsEmpty,
                //    字符类型字段如果为null,输出为"",而非null
                SerializerFeature.WriteNullStringAsEmpty,
                //    Boolean字段如果为null,输出为false,而非null
                SerializerFeature.WriteNullBooleanAsFalse,
                //    Date的日期转换器
                SerializerFeature.WriteDateUseDateFormat,
                //    循环引用
                SerializerFeature.DisableCircularReferenceDetect,
        };

        fastJsonConfig.setSerializerFeatures(serializerFeatures);
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));

        //3、在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);

        //4、将convert添加到converters中
        HttpMessageConverter<?> converter = fastConverter;

        return new HttpMessageConverters(converter);
    }
}

3、实体对象

@Data
@Accessors(chain = true)
@ApiModel(value = "demo实体类")
public class DemoEntity {

	private String name;

	private String tmail;

	private Long volumn ;

}

4、测试

  @GetMapping("get")
    @ResponseBody
    public ResponseBean get(String params){
        try {
            return ResponseBean.buildSuccess(new DemoEntity());
        } catch (AppException e) {
            log.error(e.getMessage(),e);
            return ResponseBean.buildFailure(e.getCode(),e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return ResponseBean.buildFailure(e.getMessage());
        }
    }
4.1,如果没有config的情况下

{
 "success": true,
 "result": {
     "name": null,
     "tmail": null,
     "volumn": null
     },
 "message": "",
 "code": "200",
 "date": "1556183337784"
}
4.2、如果使用了上面的,是很干净的
{
  "code": "200",
  "date": "1556183419997",
  "message": "",
  "result": {},
  "success": true
}

ContactAuthor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值