Jackson 转换JSON,SpringMVC ajax 输出,当值为null或者空不输出字段@JsonInclude
当我们提供接口的时候, Ajax 返回的时候,当对象在转换 JSON (序列化)的时候,值为Null
或者为“”
的字段还是输出来了。看上去不优雅。
现在我叙述三种方式来控制这种情况。
注解的方式( @JsonInclude(JsonInclude.Include.NON_EMPTY))
通过@JsonInclude
注解来标记,但是值的可选项有四类。
- Include.Include.ALWAYS (
Default
/ 都参与序列化) - Include.NON_DEFAULT(当
Value
为默认值的时候不参与,如Int a;
当a=0
的时候不参与) - Include.NON_EMPTY(当
Value
为“”
或者null
不输出) - Include.NON_NULL(当
Value
为null
不输出)
注解使用如下:
... ...
//如果是null 和 “” 不返回
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private T data;
... ...
我的对象定义(其实就是一个API接口的返回对象):
public class APIResult<T> implements Serializable {
//状态
private Integer status;
//描述
private String message;
//如果是null 不返回
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private T data;
/*** getter / setter***/
}
我的前端返回值:
{"status":200,"message":"success"}
如上,基本达到我的要求了。
代码方式:
ObjectMapper mapper = new ObjectMapper();
//null不序列化
mapper.setSerializationInclusion(Include.NON_NULL);
Demo demo = new Demo(200,"",null);
String json = mapper.writeValueAsString(demo);
System.out.println(json);
//结果:{"st":200,"name":""} 为null的属性没输出。
Spring配置文件实现
当我们整个项目都需要某一种规则的时候,那么我们就采用配置文件配置。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
再来一个XML配置:
<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
</bean>
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
其实所有的姿势都是针对 Jackson 提供给我们的入口“JsonInclude.Include”
来处理的。所以只要记住最上面讲的几个级别就可以了。
其实这些都是一些基础知识,我只是整合下,后面要丰富首页的内容。
版权所属:SO JSON在线解析
原文地址:https://www.sojson.com/blog/248.html
转载时必须以链接形式注明原始出处及本声明。
如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。