使用Jackson进行序列化和反序列化:如何以编程方式忽略字段? [英] Serialization and Deserialization with Jackson: how to programmatically ignore fields?

查看:253
本文介绍了使用Jackson进行序列化和反序列化:如何以编程方式忽略字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jackson来序列化和反序列化对象。问题是,有时我想显示一个字段,有时候不显示。

I'm using Jackson to serialize and deserialize objects. The problem is that sometimes I want to show a field and sometimes not.

实际上,当我不这样做时,我正在使用@JsonIgnore来避免打印属性需要它。当我需要它时,我通过

Actually I'm using the @JsonIgnore to avoid the printing of the property when I don't need it. When I need it I'm disabling the Property through

mapper.getSerializationConfig().disable(SerializationConfig.Feature.USE_ANNOTATIONS);

但这也会禁用我需要的其他注释。

but this will disable also other annotations that I need.

如何获得我需要的结果?使用视图?任何一个例子?

How can I get the result that I need? Using Views? Any example?

了解我想要的东西:

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)

and through the REST API you can get the username without the password (thanks to the JsonIgnore)

推荐答案

我认为你应该通过创建一个可以有选择地序列化/忽略的自定义Jackson序列化器来以不同的方式处理它密码。

I think you should handle this a different way, by creating a custom Jackson serializer that can selectively serialize/ignore the password.

这样的注释应该在运行时被认为是不可变的。 可能是提取 JsonIgnore 并设置值的一些反射技巧,但是,如果是这样,这将是非常严厉的。

Annotations like this should be considered immutable at runtime. There may be some reflection trick to extract the JsonIgnore and set the value, but, if so, this would be really heavy-handed.

这篇关于使用Jackson进行序列化和反序列化:如何以编程方式忽略字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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