【问题标题】:Ignore specific field on serialization with Jackson忽略 Jackson 序列化的特定字段
【发布时间】:2012-02-01 20:26:28
【问题描述】:

我正在使用 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 类的实例。我做错了什么?

【问题讨论】:

    标签: java json serialization jackson


    【解决方案1】:

    好的,所以由于某种原因我错过了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);
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-07-21
          • 2020-02-16
          • 2019-10-22
          • 1970-01-01
          • 2017-12-13
          • 2012-06-29
          • 1970-01-01
          相关资源
          最近更新 更多