如何编写条件@JsonIgnore

发布于 2025-01-08 23:36:16 字数 866 浏览 3 评论 0原文

我需要编写一个注释来忽略某些字段,但仅限于某些上下文。我希望能够将上下文值注入到 ObjectMapper 中,但我找不到任何东西。我需要使用默认的 ObjectMapper 进行完全相同的序列化工作。但在特定上下文中,我的注释将采取特殊操作(在我的例子中,相当于 @JsonIgnore)。 我认为过滤器对我不起作用,因为它不允许默认情况继续工作。我也不想根据属性名称跳过字段。我希望任何对象都能够使用 @MyJsonIgnore 进行注释 示例

通常情况

public class MyObject {
  private String field1 = "value1";
  @MyJsonIgnore
  private String field2 = "value2";

下,这会像这样序列化

ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(new MyObject());
{
   "field1": "value1",
   "field2": "value2"
}

但在我的特殊用例中,我不会得到

ObjectMapper mapper = new ObjectMapper();
mapper.setMagicalContext("context");
mapper.writeValueAsString(new MyObject());
{
   "field1": "value1"
}

field2序列化,因为它具有 @MyJsonIgnore 注释。

有什么可以做到这一点吗?

I need to write an annotation that will ignore certain fields, but only in certain contexts. I would love to be able to just inject a context value into ObjectMapper, but I can't find anything. I need the serializing to work exactly the same using the default ObjectMapper. But in a certain context, my annotation would take special action (in my case, the equivalent of @JsonIgnore).
I don't think filters would work for me, because it doesn't allow the default case to continue to work. I also don't want to skip fields based on the property name. I want any object to be able to be annotated with @MyJsonIgnore

Example

public class MyObject {
  private String field1 = "value1";
  @MyJsonIgnore
  private String field2 = "value2";

Normally, this would get serialized like this

ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(new MyObject());
{
   "field1": "value1",
   "field2": "value2"
}

But in my special use case, I would have

ObjectMapper mapper = new ObjectMapper();
mapper.setMagicalContext("context");
mapper.writeValueAsString(new MyObject());
{
   "field1": "value1"
}

field2 would not get serialized since it has the @MyJsonIgnore annotation.

Is there anything that would do this?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文