Ignore specific field on serialization with Jackson

JavaJsonSerializationJackson

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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);

Solution 2 - Java

Also worth noting is this solution using DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES: https://stackoverflow.com/a/18850479/1256179

Solution 3 - Java

Reference from https://stackoverflow.com/questions/7421474/how-can-i-tell-jackson-to-ignore-a-property-for-which-i-dont-have-control-over

You can use Jackson Mixins. For example:

class YourClass {
  public int ignoreThis() { return 0; }    
}

With this Mixin

abstract class MixIn {
  @JsonIgnore abstract int ignoreThis(); // we don't need it!  
}

With this:

objectMapper.addMixIn(YourClass.class, MixIn.class);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdison Gustavo MuenzView Question on Stackoverflow
Solution 1 - JavaEdison Gustavo MuenzView Answer on Stackoverflow
Solution 2 - JavarwblackburnView Answer on Stackoverflow
Solution 3 - JavaTongView Answer on Stackoverflow