Jackson: how can I ignore getter but parse setter?

I need to serialize a bean without a given field, but deserialize that bean with that field. I use @JsonIgnore on the getter, and @JsonIgnore(false) on the setter:

public class TestJson {     private String s1, s2;      @JsonIgnore     public String getS1() {         return s1;     }      @JsonIgnore(false)     public void setS1(String s1) {         this.s1 = s1;     }      public String getS2() {         return s2;     }      public void setS2(String s2) {         this.s2 = s2;     }      public static void main(String[] args) throws Exception {         ObjectMapper mapper = new ObjectMapper();         TestJson bean = new TestJson();         bean.setS1("test1");         bean.setS2("test2");         System.out.println(mapper.writeValueAsString(bean));          String json = "{\"s1\":\"test1\",\"s2\":\"test2\"}";         bean = mapper.readValue(json, TestJson.class);         System.out.println("s1=" + bean.getS1());         System.out.println("s2=" + bean.getS2());     } } 

The serialization works well and get the expected value {"s2":"test2"}.

But @JsonIgnore(false) on the setter does not seem to work.

I expect:

s1=test1 s2=test2 

But got:

s1=null s2=test2 

How can I make setter on field s1 work?

Add Comment
1 Answer(s)

You can use @JsonProperty with JsonProperty.Access.WRITE_ONLY

from docs

Access setting that means that the property may only be written (set) for deserialization, but will not be read (get) on serialization, that is, the value of the property is not included in serialization.

public class TestJson {      @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)     private String s1;     private String s2;       public String getS1() {         return s1;     }      public void setS1(String s1) {         this.s1 = s1;     }      public String getS2() {         return s2;     }      public void setS2(String s2) {         this.s2 = s2;     } } 

This should also work

public class TestJson {     private String s1;     private String s2;       @JsonIgnore     public String getS1() {         return s1;     }      @JsonProperty     public void setS1(String s1) {         this.s1 = s1;     }      public String getS2() {         return s2;     }      public void setS2(String s2) {         this.s2 = s2;     } } 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.