Spring MVC中用@ResponseBody转json,字段为NULL或者为空不参加序列化方法汇总

Spring MVC中,在controller层使用@ResponseBody返回json时,我这里使用的是jackson

在使用@ResponseBody注解时,返回的对象中,有的字段为空,如果想字段为空时,或者字段为默认值时,不返回该字段。有一下三种方法:

1. 在实体类上添加注解

优点方便灵活,缺点需要在每一个实体上进行配置

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class OrderDTO {
  
}

//将该标记放在属性上,如果该属性为NULL则不参与序列化 
//如果放在类上边,那对这个类的全部属性起作用 
//Include.Include.ALWAYS 默认 
//Include.NON_DEFAULT 属性为默认值不序列化 
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化 
//Include.NON_NULL 属性为NULL 不序列化 

2. 在配置文件中配置

配置完成后,所有通过@responseBody(或者@restController)转json的,都将不返回为空字段

在Spring Boot 中的application.yml配置全局定义, 这种默认都生效

spring:

   jackson:

        default-property-inclusion: non_null

在Spring MVC 中的springmvc.xml文件中配置

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <!-- 处理responseBody 里面日期类型 -->
                    <property name="dateFormat">
                        <bean class="java.text.SimpleDateFormat">
                            <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
                        </bean>
                    </property>
                    <!-- 为null字段时不显示 -->
                    <property name="serializationInclusion">
                        <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

3. 在代码中

ObjectMapper mapper = new ObjectMapper();

mapper.setSerializationInclusion(Include.NON_NULL);  

//通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化 
//Include.Include.ALWAYS 默认 
//Include.NON_DEFAULT 属性为默认值不序列化 
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化 
//Include.NON_NULL 属性为NULL 不序列化 

User user = new User(1,"",null); 
String outJson = mapper.writeValueAsString(user); 
System.out.println(outJson);


我的最新文章会先发到公众号【读钓的YY】上,欢迎关注!

发布了10 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/youthsong/article/details/78801756