com.fasterxml.jackson.annotation.JsonInclude
java.io.Serializable
@JsonInclude用法
JsonJsonInclude.Include.ALWAYS 这个是默认策略,任何情况下都序列化该字段,和不写这个注解是一样的效果。
JsonJsonInclude.Include.NON_NULL这个最常用,即如果加该注解的字段为null,那么就不序列化这个字段了,即不返回。
JsonJsonInclude.Include.NON_ABSENT这个包含NON_NULL,@JsonInclude(NON_ABSENT)可用于排除空值和“不存在”的值。此处的不存在值表示引用空值的非空引用类型值(例如java.utl.concurrent.atomic.AtomicReference)。
@JsonInclude(JsonInclude.Include.NON_ABSENT)
public class Employee {
private String name;
private String dept;
private AtomicReference<String> address;
}
public class ExampleMain {
public static void main(String[] args) throws IOException {
Employee employee = Employee.of("Trish", null, new AtomicReference<>());
ObjectMapper om = new ObjectMapper();
String jsonString = om.writeValueAsString(employee);
System.out.println(jsonString);
}
}
{"name":"Trish"}
如果我们根本不使用@JsonInclude,那么上面示例的输出将是:
{“ name”:“ Trish”,“ dept”:null,“ address”:null}
如果我们使用@JsonInclude(JsonInclude.Include.NON_NULL),则输出为:
{“ name”:“ Trish”,“ address”:null}
JsonJsonInclude.Include.NON_EMPTY 这个属性包含NON_NULL,NON_ABSENT之后还包含如果字段为空也不序列化。
JsonJsonInclude.Include.NON_DEFAULT如果字段是默认值的话就不序列化。
JsonJsonInclude.Include.CUSTOM 自定义属性过滤规则
JsonJsonInclude.Include.USE_DEFAULTS 以便可以使用更高级别的默认值。如果在属性上使用此选项@JsonInclude,则将使用类的设置(如果存在,例如某个属性设置了NON_NULL,则也是NON_NULL),否则将使用全局序列化包含规则(通过设置ObjectMapper)。
实现Serializable接口 :
对java对象进行序列化与反序列化,可与上述注解搭配使用