Ignore a specific field when serializing with Jackson

I use the Jackson library.

I want to ignore a specific field when serializing / deserializing, like for example:

public static class Foo { public String foo = "a"; public String bar = "b"; @JsonIgnore public String foobar = "c"; } 

Must give me:

 { foo: "a", bar: "b", } 

But I get:

 { foo: "a", bar: "b", foobar: "c" } 

I am serializing an object using this code:

 ObjectMapper mapper = new ObjectMapper(); String out = mapper.writeValueAsString(new Foo()); 

The real field type in my class is an instance of the Log4J Logger class. What am I doing wrong?

+52
java json jackson serialization
Jan 03 2018-12-12T00:
source share
2 answers

Ok, so for some reason I skipped 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); 
+83
Jan 03 '12 at 20:55
source share

It is also worth noting this solution using DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES: stack overflow

+1
Dec 15 '15 at 17:38
source share



All Articles