的序列化和反序列化

的序列化和反序列化

本文介绍了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?

一个小小的 pojo 来理解我想要什么:

A little pojo to understand what I want:

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 的序列化和反序列化:如何以编程方式忽略字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:37