Reputation: 100358
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?
Upvotes: 4
Views: 9568
Reputation: 2824
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; }
}
Upvotes: 14
Reputation: 18747
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);
Upvotes: 0