【问题标题】:How to globally remove attribute from Jackson JSON serialization?如何从杰克逊 JSON 序列化中全局删除属性?
【发布时间】:2012-02-09 18:01:38
【问题描述】:

我有一个对象图,其中包含(就本示例而言)类型为 Foo 的子类的对象。 Foo 类上有一个名为 bar 的属性,我不想用我的对象图对其进行序列化。所以基本上我想说的是,每当你序列化一个 Foo 类型的对象时,输出除 bar 之外的所有内容。

class Foo { // this is an external dependency
    public long getBar() { return null; } 
}

class Fuzz extends Foo {
    public long getBiz() { return null; }
}

public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();
    // I want to set a configuration on the mapper to
    // exclude bar from all things that are type Foo

    Fuzz fuzz = new Fuzz();
    System.out.println(mapper.writeValueAsString(fuzz));
    // writes {"bar": null, "biz": null} what I want is {"biz": null}
}

谢谢, 赎金

编辑:使用了 StaxMan 建议,包括我最终会使用的代码(例如,为了让 bar 成为吸气剂)

interface Mixin {
    @JsonIgnore long getBar();
}

class Example {
    public static void main() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.getSerializationConfig().addMixInAnnotations(Foo.class, Mixin.class);
        Fuzz fuzz = new Fuzz();
        System.out.println(mapper.writeValueAsString(fuzz));
        // writes {"biz": null} whoo!
    }
} 

【问题讨论】:

  • 这可能是我的无知表现,但是将 bar 标记为瞬态呢?

标签: java json jackson


【解决方案1】:

除了@JsonIgnore@JsonIgnoreProperties(尤其是通过Mix-in Annotations),您还可以使用“@JsonIgnoreType”定义全局忽略的特定类型。对于第三方类型,这也可以用作混合注释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2020-09-14
    • 2017-12-09
    相关资源
    最近更新 更多