如何编写条件@JsonIgnore
我需要编写一个注释来忽略某些字段,但仅限于某些上下文。我希望能够将上下文值注入到 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论