Jackson常用注解及用法

最近写项目,用到Jackson的一些注解,总结一下,帮助自己记忆。

1.@JsonIgnore 和 @JsonIgnoreProperties

两个注解可以对照比较后选择使用:

@JsonIgnore

在json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。

private String name;
private Integer age;
@JsonIgnore
private String color;

运行方法在控制台打印

System.out.println(name+""+age+""+color+"");

将只显示name和age,color受注解的影响不进行显示。

使用方法:一般标记在属性或者方法上,返回的json数据即不包含该属性。

@JsonIgnoreProperties

和 @JsonIgnore 的作用相同,都是告诉 Jackson 该忽略哪些属性,
不同之处是 @JsonIgnoreProperties 是类级别的,并且可以同时指定多个属性。
 
@JsonIgnoreProperties(value = {"age","color"})
public class TestJackson{
    private String id;
    private String username;
    private String password;
    private Integer age;
    private String color;
 
}
 
类中的age和color属性都将会在序列化和反序列化时被忽略掉。
 
2.@JsonProperty
 
它用于属性上,作用是把属性的名称序列化成另外一个名称
@JsonProperty("name")
private String username;
把username属性序列化为name
 
3.@JsonInclude(JsonInclude.Include.NON_NULL)
 
这个注解表示,如果值为null,则不返回,还可以在类上添加这个注释,当实体类与json互相转换的时候,属性值为null的不参与序列化
 
@JsonInclude(JsonInclude.Include.NON_NULL)
public Vector children;
 
@JsonInclude(JsonInclude.Include.NON_NULL)
public class TestJackson{
                       xxxxxx
}
 
 
原文地址:https://www.cnblogs.com/koudaiyoutang/p/9709806.html