[英]Jackson - suppressing serialization(write) of properties dynamically
I am trying to convert java object to JSON object in Tomcat/jersey using Jackson. 我正在尝试使用Jackson将Tomcat / Jersey中的Java对象转换为JSON对象。 And want to suppress serialization(write) of certain properties dynamically.
并且要动态地抑制某些属性的序列化(写)。
I can use JsonIgnore, but I want to make the ignore decision at runtime. 我可以使用JsonIgnore,但是我想在运行时做出忽略决定。 Any ideas??
有任何想法吗??
So as an example below, I want to suppress "id" field when i serialize the User object to JSON.. 因此,以下面的示例为例,当我将User对象序列化为JSON时,我想取消显示“ id”字段。
new ObjectMapper.writeValueAsString(user);
class User {
private String id = null;
private String firstName = null;
private String lastName = null;
//getters
//setters
}//end class
Yes, JSON View is the way to go. 是的,JSON View是必经之路。
If you eg need to let the client to decide which fields to marshal, this example might help: http://svn.codehaus.org/jackson/tags/1.6/1.6.3/src/sample/CustomSerializationView.java 如果您例如需要让客户决定要编组的字段,则此示例可能会有所帮助: http : //svn.codehaus.org/jackson/tags/1.6/1.6.3/src/sample/CustomSerializationView.java
Check 校验
ObjectMapper.configure(SerialiationJson.Feature f, boolean value)
and 和
org.codehaus.jackson.annotate.JsonIgnore
annotation 注解
This will work only when you want all instances of a certain type to ignore id on serialization. 仅当您希望某个类型的所有实例在序列化时忽略id时,此方法才起作用。 If you truly want dynamic (aka per instance customization) you will probabily have to hack the jackson library yourself.
如果您真正想要动态(也可以按实例自定义),则可能必须自己破解杰克逊库。
I don't see any way of doing that. 我看不到有什么办法。 If you need to dynamically decide which properties are marshalled, then I suggest you manually construct a
Map
of keys to values for your objects, and then pass that Map
to Jackson, rather than passing the User
object directly. 如果需要动态地决定将哪些属性编组,则建议您手动构造一个键
Map
到对象值,然后将该Map
传递给Jackson,而不是直接传递User
对象。
Have you tried using JSON Views ? 您是否尝试过使用JSON视图 ? Views allow annotation-based mechanism for defining different profiles, so if you just need slightly differing views for different users, this could work for you.
视图允许使用基于注释的机制来定义不同的配置文件,因此,如果您仅需要针对不同用户的略有不同的视图,则可以使用该视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.