杰克逊:基于其属性从序列化中排除对象 [英] Jackson: exclude object from serialization based on its properties

查看:141
本文介绍了杰克逊:基于其属性从序列化中排除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

杰克逊根据其属性从序列化中排除对象的最简单方法是什么?

What is the easiest way in Jackson to exclude an object from serialization based on its properties?

例如,假设一个实例 o C 有一个布尔值启用字段。如果 o.enabled == false ,那么该对象不应该被序列化。

e.g., say an instance o of class C has a boolean enabled field. If o.enabled == false, then the object shouldn't be serialized.

另外,我怎么能使这项工作与当前的JSON视图一起使用?例如,假设一个实例 o C 有一个 boolean topSecret 字段。如果 o.topSecret == true ,并且当前JSON View不是 TopSecret.class ,那么该对象不应该不能序列化。

Also, how can I make this work in conjunction with the current JSON View? e.g., say an instance o of class C has a boolean topSecret field. If o.topSecret == true, and if the current JSON View is not TopSecret.class, then the object shouldn't be serialized.

推荐答案

这样做没有直接的功能,因为序列化工作的方式,值对象本身不能决定是否要序列化。这主要是因为属性名称可能已经被写入,因此必须将某些内容写为值。
相反,它是确定包含/排除的对象属性。

There is no direct functionality for doing this, because the way serialization works, value objects themselves can not decide if they want to be serialized or not. This is mostly because property name may already have been written, so something must be written as a value. Rather, it is Object properties that determine inclusion/exclusion.

这样,JSON过滤器( http://www.cowtowncoder.com/blog/archives/2011/09/entry_461.html )也许可以工作您。 JSON视图太静态而不允许控制级别。

With this, JSON Filters (http://www.cowtowncoder.com/blog/archives/2011/09/entry_461.html) could perhaps work for you. JSON Views are too static to allow level of control.

另一种可能性是尝试使用处理 @JsonInclude JsonSerializer isEmpty(...)方法,用于检查序列化程序处理类型的对象是否被视为空 ,可能被排除在序列化之外。如果您需要处理的类型数量有限,这可能会有效。然而,基于原始问题,情况可能并非如此。

Another possibility could be to try to use machinery that deals with @JsonInclude. JsonSerializer has isEmpty(...) method that is used to check whether object of type serializer handles is considered "empty", and possibly excluded from serialization. If number of types you need to handle is limited, this might work. However based on the original question this is probably not the case.

另一种可能性是进行两阶段处理:首先将POJO转换为树模型( JsonNode ),然后遍历它,删除不应包含的内容。然后,序列化树模型。

Yet another possibility is to do two-phase processing: first convert POJOs into Tree Model (JsonNode), then traverse it, remove whatever should not be included. And after this, serialize tree model.

这篇关于杰克逊:基于其属性从序列化中排除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆