SpringMVC 中⽤@ResponseBody 转json ,字段为NULL 或者为空不参加序。。。
Spring MVC中,在controller层使⽤@ResponseBody返回json时,我这⾥使⽤的是jackson。
在使⽤@ResponseBody注解时,返回的对象中,有的字段为空,如果想字段为空时,或者字段为默认值时,不返回该字段。有⼀下三种⽅法:
1. 在实体类上添加注解
优点⽅便灵活,缺点需要在每⼀个实体上进⾏配置
2. 在配置⽂件中配置
配置完成后,所有通过@responseBody(或者@restController)转json的,都将不返回为空字段
在Spring Boot 中的l配置全局定义, 这种默认都⽣效
在Spring MVC 中的l⽂件中配置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 不序列化
1
2
3
4
5
6
7
8
9
10
11
12
13spring :  jackson:        default -property-inclusion: non_null
1
2
3
4
5
3. 在代码中<mvc:annotation-driven >    <mvc:message-converters >        <bean  class ="org.verter.json.MappingJackson2HttpMessageConverter">            <property  name ="objectMapper">                <bean  class ="com.fasterxml.jackson.databind.ObjectMa
pper">                    <!-- 处理responseBody ⾥⾯⽇期类型 -->                    <property  name ="dateFormat">                        <bean  class ="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 >
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mvc的controller19
20ObjectMapper 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);
1
2
3
4
5
6
7
8
9
10
11
12
13