I'm using the Jackson library.
I want to ignore a specific field when serializing/deserializing, so for example:
public static class Foo { public String foo = "a"; public String bar = "b"; @JsonIgnore public String foobar = "c"; }
Should give me:
{ foo: "a", bar: "b", }
But I'm getting:
{ foo: "a", bar: "b", foobar: "c" }
I'm serializing the object with this code:
ObjectMapper mapper = new ObjectMapper(); String out = mapper.writeValueAsString(new Foo());
The real type of the field on my class is an instance of the Log4J Logger class. What am I doing wrong?
The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.
Ignore All Fields by Type Finally, we can ignore all fields of a specified type, using the @JsonIgnoreType annotation. If we control the type, then we can annotate the class directly: @JsonIgnoreType public class SomeType { ... } More often than not, however, we don't have control of the class itself.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
If the field has a default value it will not be changed during deserialization. Even if JSON contains a new value for it. The annotation JsonProperty with READ_ONLY tells deserializer to keep the old value of the property during deserialization.
Ok, so for some reason I missed this answer.
The following code works as expected:
@JsonIgnoreProperties({"foobar"}) public static class Foo { public String foo = "a"; public String bar = "b"; public String foobar = "c"; } //Test code ObjectMapper mapper = new ObjectMapper(); Foo foo = new Foo(); foo.foobar = "foobar"; foo.foo = "Foo"; String out = mapper.writeValueAsString(foo); Foo f = mapper.readValue(out, Foo.class);
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