Search code examples
javajackson

Convert hashmap to json while filtering some keys?


I am trying to convert hashmap to json while filtering some keys. I have tried with Jackson but the result always have all the keys in it.

Map<String, String> hashtable = new HashMap();
hashtable.put("KEY1", "VALUE1");
hashtable.put("KEY2", "VALUE2");
hashtable.put("KEY3", "VALUE3");

ObjectMapper objectMapper = new ObjectMapper();
FilterProvider filter = new SimpleFilterProvider().addFilter("filter", SimpleBeanPropertyFilter.filterOutAllExcept("KEY1"));
objectMapper.setFilterProvider(filter);
System.err.println(objectMapper.writeValueAsString(hashtable));

My keys are dynamic, Is there more efficent way to do this?

Jackson method of filtering is perfect to me, since i need to generate multiple json's with different filter for the same HashMap. Is is possible to make this work with Jackson?


Solution

  • Here is the answer of your question. You should create mixinSource Class without any fields and add it to the objectMapper. Then you can filter out your map dynamically

    @JsonFilter("filter")
    public class DynamicMixIn {
    
    }
    
    Map<String, String> hashtable = new HashMap();
    hashtable.put("KEY1", "VALUE1");
    hashtable.put("KEY2", "VALUE2");
    hashtable.put("KEY3", "VALUE3");
    
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixIn(Object.class, DynamicMixIn.class);
    FilterProvider filter = new SimpleFilterProvider().addFilter("filter", SimpleBeanPropertyFilter.serializeAllExcept("KEY1"));
    objectMapper.setFilterProvider(filter);
    String filtered = objectMapper.writeValueAsString(hashtable); // {"KEY2":"VALUE2","KEY3":"VALUE3"}