首页 > 解决方案 > Jackson Mixin 在使用 @JsonUnwrapped 时忽略一个属性,但仅在某些情况下

问题描述

对于 Jackson,我使用 Mixin 接口进行序列化。

假设我有一个由多个类使用的公共类,这里是该类的 Mixin:

@JsonPropertyOrder({"id", "name"})
interface SharedMixin {
    String getId();

    String getName();
}

该 Mixin 被多个使用 @JsonUnwrapped 注释的 Mixin 使用,如下所示:

@JsonPropertyOrder({"code", "sharedMixin"})
public interface AnotherMixin {
  String getCode();

  @JsonUnwrapped
  SharedMixin getSharedMixin();
}

这很好用,它解开了 SharedMixin 接口中的所有属性。但是有一种特殊情况,我想在父 Mixin 中展开时忽略 SharedMixin 的一个属性,假设我想忽略 name 字段。我尝试了以下但没有成功。

@JsonPropertyOrder({"otherField", "sharedMixin"})
public interface AnotherMixin2 {
  String otherField();

  @JsonUnwrapped
  SharedMixin getSharedMixin();

  @JsonIgnore()
  String getName();
}

我也尝试过使用“@JsonIgnoreProperties({"name"})”,但它都不起作用,看起来该属性在序列化时仍然存在,但值为空。

请注意,我不能在 SharedMixin 中使用 @JsonIgnore() ,因为它会忽略所有使用它的类中的字段并且它们是多个。

标签: jacksonjackson2

解决方案


看起来这是杰克逊图书馆中的一个错误,@JsonUnwrapped 和 @JsonIgnoreProperties 不能很好地协同工作。

https://github.com/FasterXML/jackson-dataformats-text/issues/77


推荐阅读