Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore specific field on serialization with Jackson

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?

like image 623
Edison Gustavo Muenz Avatar asked Jan 03 '12 20:01

Edison Gustavo Muenz


People also ask

How do I ignore a field in JSON response Jackson?

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.

How do I ignore properties in Jackson?

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.

How do you ignore property serializable?

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.

How do I ignore JSON property while deserialization?

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.


1 Answers

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); 
like image 106
Edison Gustavo Muenz Avatar answered Sep 20 '22 07:09

Edison Gustavo Muenz