简体   繁体   中英

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.

Say, I have the POJO below. I want to include NULLs when "show" is true, and exclude NULLS when "show" is false. Be aware that the actual Object I am trying to Serialize has over 30 properties.

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? 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. For that you can create a ObjectMapper with NULL serialisation settings based on your show property and then delegate the serialisation to it.

I have a similar requirement and probably I'll be acquainting myself with the actual APIs of Object Mapper. I'll try to post the code for the above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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