Ignore specific field on serialization with Jackson
Asked Answered
A

4

63

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?

Ablaut answered 3/1, 2012 at 20:45 Comment(0)
A
91

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);
Ablaut answered 3/1, 2012 at 20:55 Comment(0)
C
1

Also worth noting is this solution using DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES: https://mcmap.net/q/143554/-how-can-i-tell-jackson-to-ignore-a-property-for-which-i-don-39-t-have-control-over-the-source-code

Cummine answered 15/12, 2015 at 17:38 Comment(0)
A
0

Reference from How can I tell jackson to ignore a property for which I don't have control over the source code?

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);
Anthurium answered 8/8, 2018 at 19:0 Comment(0)
W
0

try to ignore the get method, and use the set method. e.g.

@JsonIgnore
public String getPassword() {
    return _password;
}

@JsonProperty(JSON.PASSWORD)
public void setPassword(String value) {
    _password = value;
}

Worked in my test case.

The idea is the deserializer can write the value, but the serializer should not see the value.

Whitefaced answered 11/6 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.