@JsonIninclude 按类过滤'属性

发布于 2025-01-13 07:55:41 字数 1035 浏览 5 评论 0原文

我正在致力于将类序列化为 XML。我发现 @JsonInclude 非常有帮助。但是,我在按属性过滤类时遇到问题。在 xml 中,如果是美国地址,我需要使用 @JsonProperty 为字段提供一组注释。因此,我尝试使用 Include 注释来仅显示基于国家/地区的相关字段。

美国地址需要使用 USAddress 作为包装元素名称。外部地址需要使用 ForeignAddress 作为包装器元素名称以及 state/zip 的不同元素名称。

有没有办法访问过滤器中的类及其属性?我尝试过对两种类型的地址使用超类,但是使用 Bazel 时,我遇到了循环依赖问题。我对 bazel 非常陌生:P

public class Thing {
  @JsonInclude(value = Include.CUSTOM, valueFilter = CountryFilter.class)
  private final USAddress usAddress = new USAddress({line1: "123 MockingBird Ln", country: "US"});
  @JsonInclude(value = Include.CUSTOM, valueFilter = CountryFilter.class)
  private final ForeignAddress foreignAddress = new ForeignAddress({line1: "123 MockingBird Ln", country: "DE"});
}

public class CountryFilter {
  @Override
  public boolean equals(Object obj) {
    return ...; // This is where I'm having issues. Would like it to do something like obj.getCountry().equals("US").
  }
}

I am working on serializing classes to XML. I've found @JsonInclude to be immensely helpful. However, I am having issues on filtering a class by its attribute. In the xml, if it's a US address I need to have one set of annotations for the fields using @JsonProperty. Because of this, I'm trying to use the Include annotation to only show the relevant field based on the country.

The US address needs to have USAddress as the wrapper element name. Foreign Addresses need to have ForeignAddress as the wrapper element name as well as different element names for state/zip.

Is there a way to access the class and it's attributes in the filter? I've tried using the super class for both types of addresses, but with Bazel, I run into circular dependency issues when doing that. Im super new to bazel :P

public class Thing {
  @JsonInclude(value = Include.CUSTOM, valueFilter = CountryFilter.class)
  private final USAddress usAddress = new USAddress({line1: "123 MockingBird Ln", country: "US"});
  @JsonInclude(value = Include.CUSTOM, valueFilter = CountryFilter.class)
  private final ForeignAddress foreignAddress = new ForeignAddress({line1: "123 MockingBird Ln", country: "DE"});
}

public class CountryFilter {
  @Override
  public boolean equals(Object obj) {
    return ...; // This is where I'm having issues. Would like it to do something like obj.getCountry().equals("US").
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

┊风居住的梦幻卍 2025-01-20 07:55:41

我最终使用了 @JsonInclude(Include.NON_NULL) ,然后在构造函数中使用条件来选择设置地址。

I ended up using the @JsonInclude(Include.NON_NULL) and then used a conditional in the constructor to optionally set the address.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文