2

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?

auntyellow
  • 2,423
  • 2
  • 20
  • 47
  • remove `@JsonIgnore(false)` from setter method, you don't need it – Ryuzaki L Jul 14 '20 at 14:02
  • @Deadpool , but I need to deserialize this bean with field "s1" (i.e. I need Jackson deserialize both field "s1" and "s2"). Removal of `@JsonIgnore(false)` can't work. – auntyellow Jul 14 '20 at 14:06
  • It should work, have you tried ? and any error message ? – Ryuzaki L Jul 14 '20 at 14:07
  • @Deadpool , I tried with `com.fasterxml.jackson.core:jackson-databind:2.10.0`, and always get `s1=null \n s2=test2` (I expect `s1=test1 \n s2=test2`). Have you tried and what Jackson version you are using? – auntyellow Jul 14 '20 at 14:16

1 Answers1

2

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;
    }
}
deadshot
  • 8,881
  • 4
  • 20
  • 39