您的位置:首页 > 编程语言 > Java开发

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

2017-12-14 13:47 429 查看
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>
&
4000
lt;/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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: