JsonIgnore on Field vs JsonIgnore on getter in Jackson

Sag*_*gar 5 java jackson java-8 jackson2

是什么区别JsonIgnore在现场VSJsonIgnore在现场的杰克逊的吸?

Dea*_*ool 7

@JsonIgnore注解用于忽略来自反序列化和序列化的字段,它可以直接放在实例成员或其 getter 或 setter 上。在这 3 点中的任何一点中应用注释,都会导致从序列化和反序列化过程中完全排除该属性(这适用​​于 Jackson 1.9;这些示例中使用的版本是 Jackson 2.4.3) .

注意:在 1.9 版本之前,这个注解纯粹是在逐个方法(或逐个字段)的基础上工作的;对一个方法或字段的注释并不意味着忽略其他方法或字段

例子

 import java.io.IOException;

 import com.fasterxml.jackson.annotation.JsonIgnore;
 import com.fasterxml.jackson.core.JsonParseException;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.JsonMappingException;
 import com.fasterxml.jackson.databind.ObjectMapper;

 class MyTestClass {

 private long id;
 private String name;
 private String notInterstingMember;
 private int anotherMember;
 private int forgetThisField;

 public long getId() {
    return this.id;
 }

 public void setId(long id) {
     this.id = id;
 }

 public String getName() {
     return this.name;
 }

 public void setName(String name) {
    this.name = name;
 }

 @JsonIgnore
 public String getNotInterstingMember() {
    return this.notInterstingMember;
 }

 public void setNotInterstingMember(String notInterstingMember) {
    this.notInterstingMember = notInterstingMember;
 }

 public int getAnotherMember() {
    return this.anotherMember;
 }

 public void setAnotherMember(int anotherMember) {
    this.anotherMember = anotherMember;
 }

 public int getForgetThisField() {
    return this.forgetThisField;
 }

 @JsonIgnore
 public void setForgetThisField(int forgetThisField) {
    this.forgetThisField = forgetThisField;
 }

 @Override
 public String toString() {
    return "MyTestClass [" + this.id + " , " +  this.name + ", " + this.notInterstingMember + ", " + this.anotherMember + ", " + this.forgetThisField + "]";
    }

  }
Run Code Online (Sandbox Code Playgroud)

输出:

 {"id":1,"name":"Test program","anotherMember":100}
 MyTestClass [1 , Test program, null, 100, 0]
Run Code Online (Sandbox Code Playgroud)

但是仍然可以更改此行为并使其不对称,例如仅使用@JsonIgnore注释和另一个名为的注释从反序列化中排除属性@JsonProperty.