忽略Jackson的序列化特定字段

时间:2012-01-03 20:45:05

标签: java json serialization jackson

我正在使用杰克逊图书馆。

我想在序列化/反序列化时忽略特定字段,例如:

public static class Foo {
    public String foo = "a";
    public String bar = "b";

    @JsonIgnore
    public String foobar = "c";
}

应该给我:

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

但我得到了:

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

我正在用这段代码序列化对象:

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

我班上该字段的真实类型是Log4J Logger类的一个实例。我做错了什么?

3 个答案:

答案 0 :(得分:86)

好的,所以出于某种原因,我错过了this answer

以下代码按预期工作:

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

答案 1 :(得分:1)

另外值得注意的是这个解决方案使用DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES:https://stackoverflow.com/a/18850479/1256179

答案 2 :(得分:0)

来自How can I tell jackson to ignore a property for which I don't have control over the source code?的引用

您可以使用Jackson Mixins。例如:

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

有了这个Mixin

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

与此:

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