如何在Jackson JSON序列化中全局移除属性?

4

我有一个对象图,其中包含对象,这些对象是(针对此示例)类型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}
}

谢谢, Ransom

编辑:使用了StaxMan的建议,包括我最终会使用的代码(并将bar作为示例的getter)。

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标记为瞬态如何? - DwB
1个回答

3

除了使用@JsonIgnore@JsonIgnoreProperties(尤其是通过混合注释),您还可以使用@JsonIgnoreType定义要在全局忽略的特定类型。 对于第三方类型,这也可以作为混入注释应用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接