如何正确使用Jackson @JSONView从默认序列化中排除特定属性? [英] How to correctly use Jackson @JSONView to exclude specific properties from default serialization?

查看:187
本文介绍了如何正确使用Jackson @JSONView从默认序列化中排除特定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个像这样的JSON映射类:

Given a JSON-mapped class like this:

public class Person {
    @JsonProperty
    String getName() { ... }

    @JsonProperty @JsonView(SpecialView.class)
    String getId() { ... }
}

在使用normal时,我只需要包含 name 属性序列化(即,没有指定视图),并在使用 SpecialView 进行序列化时包含这两个属性。但当我这样做时

I need to include only the name property when when using "normal" serialization (ie, no view specified), and include both properties when serializing using SpecialView. But when I do

objectMapper.writeValueAsString(object)

(即,未指定任何视图),包含 id 属性。

(ie, not specifying any view), the id property is included.

如果我这样做

objectMapper..writerWithView(Object.class).writeValueAsString(object)

然后它按预期运行。问题是,我没有控制所有正在进行序列化的代码,所以我不能强制它指定一个视图。

then it behaves as expected. Problem is, I don't control all the code that's doing serialization so I can't force it all to specify a view.

当我逐步完成Jackson源代码(v 2.5.4),我看到 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields()不使用 _filteredProps 如果没有活动视图:

When I stepped through the Jackson source code (v 2.5.4), I see that com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields() does not use the _filteredProps if there is no "active view":

    if (_filteredProps != null && provider.getActiveView() != null) {
        props = _filteredProps;
    } else {
        props = _props;
    }

序列化不尊重 @JsonView似乎很奇怪未指定视图时。我错过了什么吗?

It seems strange that serialization would not respect @JsonView when no view is specified. Am I missing something?

有没有办法达到我的目的?

Is there a way to achieve what I want?

推荐答案

我碰到了同样的问题。除非指定了视图,否则杰克逊似乎完全忽略@JsonView注释。为了获得你所处的行为,给你的mapper一个默认的Object.class视图。

I ran across the same problem. It seems like Jackson totally ignores @JsonView annotations unless a view is specified. To get the behaviour you are after give your mapper a default view of Object.class.

mapper.setConfig(mapper.getSerializationConfig().withView(Object.class));

请注意,您也可以使用

mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

这是杰克逊2.6.3

This is with Jackson 2.6.3

这篇关于如何正确使用Jackson @JSONView从默认序列化中排除特定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆