简体   繁体   English

如何使用Jackson将POJO序列化为JSON?

[英]How to serialise POJO to json differently using Jackson?

I have a POJO that I want to Serialize differently based on a value of one of the properties. 我有一个POJO,我想根据属性之一的值进行不同的序列化。

Say, I have the POJO below. 说,我下面有POJO。 I want to include NULLs when "show" is true, and exclude NULLS when "show" is false. 我想在“ show”为true时包括NULL,而在“ show”为false时排除NULL。 Be aware that the actual Object I am trying to Serialize has over 30 properties. 请注意,我要序列化的实际对象具有30多个属性。

public class User {
    @JsonIgnore
    private boolean show;

    private String name;
    private Integer age;
    ...
    ...
}

I would like to know how to do that using Jackson. 我想知道如何使用杰克逊做到这一点。 Do I have to implement my own JsonSerializer, or should I create a PropertyFilter? 我是否必须实现自己的JsonSerializer,还是应该创建一个PropertyFilter? Or have I missed an out of the box feature? 还是我错过了开箱即用的功能?

You can write your own custom serialiser that takes care of the generation of null properties based on the show instance variable. 您可以编写自己的自定义序列化程序,该序列化程序负责根据show实例变量生成null属性。 For that you can create a ObjectMapper with NULL serialisation settings based on your show property and then delegate the serialisation to it. 为此,您可以基于show属性创建具有NULL序列化设置的ObjectMapper ,然后将序列化委托给它。

I have a similar requirement and probably I'll be acquainting myself with the actual APIs of Object Mapper. 我有一个类似的要求,也许我会熟悉Object Mapper的实际API。 I'll try to post the code for the above. 我将尝试发布上面的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM