简体   繁体   English

如何从Jackson JSON序列化全局删除属性?

[英]How to globally remove attribute from Jackson JSON serialization?

I have an object graph that contains objects that are (for purposes of this example) subclasses of type Foo. 我有一个对象图,其中包含一些对象(出于本示例的目的)是Foo类型的子类。 The Foo class has an attribute on it called bar that I do not want to be serialized with my object graph. Foo类上有一个称为bar的属性,我不想与我的对象图序列化。 So basically I want a way to say, whenever you serialize an object of type Foo, output everything but 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}
}

Thanks, Ransom 谢谢,赎金

Edit: Used StaxMan suggestion, including code that I would end up using (and made bar a getter for example's sake) 编辑:使用了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!
    }
} 

Aside from @JsonIgnore or @JsonIgnoreProperties (esp. via Mix-in Annotations ), you can also define specific types to be globally ignored with '@JsonIgnoreType'. 除了@JsonIgnore@JsonIgnoreProperties (尤其是通过混入注释 ),您还可以定义特定的类型,以使用'@JsonIgnoreType'全局忽略。 For third-party types, this too can be applied as a mix-in annotation. 对于第三方类型,也可以将其用作混合注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM