【问题标题】:Is there something like @JsonIgnoreOtherProperties?有没有像@JsonIgnoreOtherProperties 这样的东西?
【发布时间】:2016-12-19 13:50:31
【问题描述】:

Jackson 在字段级别有 @JsonIgnoreProperties 注释,这很棒,但有时它可能很大。

@JsonIgnoreProperties({ "name", "phone", ... "20th item"})
private User user;

我正在寻找类似的东西:

@JsonIgnoreOtherProperties("email")
private User user;

所以这会忽略除电子邮件以外的所有字段。

有类似@JsonIgnoreOtherProperties 的东西吗?

【问题讨论】:

    标签: java json serialization jackson deserialization


    【解决方案1】:

    我认为不存在,但有几种方法可以实现您想要的(除了您现有的解决方案):

    1) 使用@JsonView (http://wiki.fasterxml.com/JacksonJsonViews)。示例见What is the JSON View class in Jackson and how does it work?

    2) 创建一个不同的User 视图,其中包含一组最小字段,可能是UserMinimal。它可能继承自一个公共接口作为您的其他 User 视图,以表明它们确实代表同一个实体。

    3) 自定义对象映射器并使用过滤器。示例见How do I exclude fields with Jackson not using annotations?

    就个人而言,如果您有一个简单的用例,我更喜欢第一种解决方案,如果您有一个更复杂的用例,我更喜欢第二种解决方案。我不喜欢第三个选项,因为根据我的经验,我认为自定义对象映射器会导致容易出错。

    不过,您的注释想法听起来很有趣。我会考虑把它作为一个功能请求(我认为它会去https://github.com/FasterXML/jackson-annotations/issues)。

    【讨论】:

      猜你喜欢
      • 2013-07-30
      • 2014-09-29
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多