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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With