使用Jackson进行序列化和反序列化:如何以编程方式忽略字段?
我正在使用Jackson来序列化和反序列化对象。 问题是有时候我想要显示一个字段,有时候不显示。
实际上我正在使用@JsonIgnore来避免在我不需要时打印属性。 当我需要它时,我正在禁用该物业
mapper.getSerializationConfig().disable(SerializationConfig.Feature.USE_ANNOTATIONS);
但是这也会禁用我需要的其他注释。
我怎样才能得到我需要的结果? 使用视图? 任何例子?
有点儿了解我想要的东西:
class User { private String username; @JsonIgnore private String password; // getter setter } writeToDB() { mapper.getSerializationConfig().disable(SerializationConfig.Feature.USE_ANNOTATIONS); mapper.writeValueAsString(user); }
通过REST API,您可以获得没有密码的用户名(感谢JsonIgnore)
我认为你应该通过创建一个可以选择性地序列化/忽略密码的自定义Jackson序列化器来以不同的方式处理这个问题。
像这样的注释应该在运行时被认为是不可变的。 可能有一些reflection技巧来提取JsonIgnore
并设置值,但是,如果是这样,这将是非常严厉的。
最后,我以不同的方式处理了这个问题。 我使用的是Jersey和Guice所以有点难以找到,但我做到了。
基本上我使用了Jackson的MixIn注释,但是使用Jersey我必须将ObjectMapper创建为Provider,然后将其与Guice绑定。
这样当我使用REST服务时,Jersey将使用Provider中定义的ObjectMapper; 当存储东西时,Jackson将使用标准的ObjectMapper。
现在一些代码。
创建PrivateUser类:
public abstract class PrivateUser { @JsonIgnore abstract String getPassword(); }
创建提供者:
@Provider public class JacksonMixInProvider implements ContextResolver { @Override public ObjectMapper getContext(Class> aClass) { final ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().addMixInAnnotations(User.class, PrivateUser.class); return mapper; } }
绑定它:
bind(JacksonMixInProvider.class).asEagerSingleton();
而已! :d
希望这会帮助别人浪费更少的时间!
- jackson – 反序列化通用类变量
- 找不到com.fasterxml.jackson.core.JsonParseException的类文件
- Spring @JsonIgnore无法正常工作
- 如何从FasterXML \ Jackson序列化/反序列化布尔值作为Int?
- 无法在Jersey 2.0中为Jackson启用基于POJO的JSON绑定支持
- jackson,序列化参考的一个属性
- Spring 3使用Jackson将ArrayList序列化为JSON而不包装到对象(没有名称)
- 使用Jongo和MongoDB在Jackson反序列化中将ObjectId _id重命名为id
- 在序列化对象时,如何强制Jackson将数字写为字符串