Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson ignore fields when writing

Tags:

java

jackson

I'm reading this object from JSON using the Jackson library:

{
    a = "1";
    b = "2";
    c = "3";
}

I'm parsing this by using mapper.readValue(new JsonFactory().createJsonParser(json), MyClass.class);

Now I want to print the object to JSON, using mapper.writeValueAsString(object), but I want to ignore the 'c' field. How can I achieve this? Adding @JsonIgnore to the field would prevent the field from being set while parsing, wouldn't it?

like image 216
nhaarman Avatar asked Dec 16 '22 11:12

nhaarman


1 Answers

You can't do this by using public fields, you have to use methods (getter/setter). With Jackson 1.x, you simply need to add @JsonIgnore to the getter method and a setter method with no annotation, it'll work. Jackson 2.x, annotation resolution was reworked and you will need to put @JsonIgnore on the getter AND @JsonProperty on the setter.

public static class Foo {
    public String a = "1";
    public String b = "2";
    private String c = "3";

    @JsonIgnore
    public String getC() { return c; }

    @JsonProperty // only necessary with Jackson 2.x
    public String setC(String c) { this.c = c; }
}
like image 134
Pascal Gélinas Avatar answered Dec 30 '22 02:12

Pascal Gélinas