IT袋

当前位置:主页 > 经验教程 > 建站编程 >

接口返回值如何去掉空字段

接口返回值如何去掉空字段? 如何在接口返回值中去除空字段?(2)

时间:2024-01-09 15:56:58 来源:IT袋 作者:马勇
导读:接口返回值如何去掉空字段,/** * @Author: springboot * @Github: https://github.com/bangbangzhou * @description: TODO */@Configurationpublic class JacksonConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper objectMap

接口返回值如何去掉空字段

/**
 * @Author: springboot
 * @Github: https://github.com/bangbangzhou
 * @description: TODO
 */
@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 设置在序列化时不包括值为null的字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 其他定制配置,根据需要添加
        return objectMapper;
    }
}

这个配置类使用ObjectMapper来配置Jackson的一些特性,其中setSerializationInclusion(JsonInclude.Include.NON_NULL)将在序列化时排除掉值为null的字段。

注意:SpringBoot使用HttpMessageConverter接口转换HTTP请求和响应。开箱即用中包含明智的默认设置。

例如,可以将对象自动转换为JSON(通过使用Jackson库)默认情况下,字符串以UTF-8编码。

2.Fastjson去空值

fastjson是阿里开源的高性能JSON序列化框架,虽然fastjson有一些bug,但有些项目还在大量使用。

如果使用的是Fastjson作为JSON序列化库,需要通过配置FastJsonHttpMessageConverter和FastJsonConfig来实现在接口返回值中去掉空字段

@Configuration
public class MyFastjsonConfig {
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters(){
        //1、先定义一个convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
        //2、添加fastjson的配置信息,比如是否要格式化返回的json数据;
        FastJsonConfig fastJsonConfig=new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //3、在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter=fastConverter;
        return new HttpMessageConverters(converter);
    }
}

上述就是接口返回值如何去掉空字段?的具体介绍,小编希望给网友们带来一些知识。

相关阅读