@JsonFilter throws “JsonMappingException: Can not resolve BeanPropertyFilter”

后端 未结 4 1271
無奈伤痛
無奈伤痛 2021-01-01 17:46

Is it possible to selectively determine when the @JsonFilter annotation gets used at runtime?

I\'m getting JsonMappingException exception (see below) when I don\'t p

4条回答
  •  不知归路
    2021-01-01 17:58

    I think you could trick the filtered writer defining an empty serialize filter for the cases where you want all the properties seralized:

    FilterProvider filters = new SimpleFilterProvider().addFilter("apiFilter", SimpleBeanPropertyFilter.serializeAllExcept(emptySet));
    

    This way, when the engine looks for the "apiFilter" filter defined at the @JsonFilter anotation, it finds it, but it will not have any effect (as will serialize all the properties).

    EDIT Also, you can call the factory method writer() instead of filteredWriter():

    ObjectWriter writer=null;
    if(aplyFilter) {
        FilterProvider filters = new SimpleFilterProvider().addFilter("apiFilter", SimpleBeanPropertyFilter.filterOutAllExcept(filterProperties));
        writer=mapper.filteredWriter(filters);
    } else {
       writer=mapper.writer();
    }
    
    return writer.writeValueAsString(user);
    

    I think this last solution is way cleaner, and indeed better.

提交回复
热议问题