Search code examples
javajsonserializationjackson2

Serializing a POJO based on a runtime whitelist of properties


Is it possible to serialize a whitelisted subset of a POJO's properties (where the whitelist is known only at runtime) using Jackson?

All the solutions I know of so far (Views, @JsonIgnoreProperties etc.) are static, compile-time solutions.

Further, my backend returns results in the following format:

{
    "outcome": "SUCCESS", // an enum
    "message": "Success.", // a message for the developer
    "result": {
        // Some result that's different for each call
    }
}

So I am looking for a solution that can be applied to only parts of the object graph (like the contents of the result property).


Solution

  • You probably want to look at @JsonFilter.

    See this tutorial on serializing only fields that meet some criteria which includes details of this, and a couple of other methods.

    For completeness

    @JsonFilter("pojo-filter")
    class Pojo {
        public int foo;
    }
    
    FilterProvider filters = new SimpleFilterProvider()
        .addFilter("pojo-filter", new SimpleBeanPropertyFilter() {
            @Override
            protected boolean include(PropertyWriter writer) {
                return "foo".equals(writer.getName()) 
                    ? Random.nextBoolean()
                    : true;
            }
        });
    
    new ObjectMapper().writer().filters(filters).write(new Pojo());
    

    Globally you can use ObjectMapper.setFilterProvider