简体   繁体   中英

Jackson ignore fields when writing

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?

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; }
}

You can use @JsonIgnoreProperties({"c"}) while serializing the object.

@JsonIgnoreProperties({"c"})
public static class Foo {
    public String a = "1";
    public String b = "2";
    public String c = "3";
}

//Testing
ObjectMapper mapper = new ObjectMapper();
Foo foo = new Foo();
foo.a = "1";
foo.b = "2";
foo.c = "3";
String out = mapper.writeValueAsString(foo);
Foo f = mapper.readValue(out, Foo.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM