且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Jackson 以两种不同的方式序列化一个类

更新时间:2023-01-17 08:35:21

从选项来看,您似乎可以注释属性,以便仅在将给定的 View 传递给 时才显示该属性ObjectMapper 用于序列化.您可以因此编辑类:

From looking at options, it seems you can annotate properties to only be shown if a given View is passed to the ObjectMapper used for serialization. You could thus edit the class:

public static class FooReference {
    public DBRef<Foo> foo;

    @JsonView(Views.WebView.class)
    public Foo getFoo() {
        return foo.fetch();
    }
}

并提供:

class Views {
    static class WebView { }
}

然后在使用正确视图创建配置后进行序列化:

and then serialize after creating a configuration with the correct view:

SerializationConfig conf = objectMapper.getSerializationConfig().withView(Views.WebView.class);
objectMapper.setSerializationConfig(conf);

然后将其序列化.在使用 MongoDB 包装器序列化时不指定视图将意味着该方法将被忽略.没有 JsonView 注释的属性默认是序列化的,你可以通过指定来改变这种行为:

Which would then serialize it. Not specifying the view when serializing with the MongoDB wrapper would mean the method would be ignored. Properties without a JsonView annotation are serialized by default, a behaviour you can change by specifying:

objectMapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);

在杰克逊维基上提供了更多信息.

事实证明,还有其他选择:有 Jackson MixIns 可以让您在不修改类本身的情况下覆盖(反)类部分的序列化行为,从 Jackson 2.0(最新版本)开始,有 过滤器,也是.

There are still other alternatives, too, it turns out: there are Jackson MixIns which would let you override (de)serialization behaviour of parts of a class without modifying the class itself, and as of Jackson 2.0 (very recent release) there are filters, too.