@JsonFilter throws “JsonMappingException: Can not resolve BeanPropertyFilter”

后端 未结 4 1269
無奈伤痛
無奈伤痛 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 18:18

    I had a similar issue getting the same Exception, but the accepted answer didn't really help in my case. Here's the solution that worked for me:

    In my setup I was using a custom JacksonSerializer like this:

    @JsonSerialize(using = MyCustomSerializer.class)
    private Object someAttribute;
    

    And that serializer was implemented like this:

    public class MyCustomSerializer extends JsonSerializer {
      @Override
      public void serialize(Object o, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        if (o != null) {
          jgen.writeObject(o);
        }
      }
    }
    
    
    

    The problem with this is, that as long as you don't use any filters, it works. It also works if you serialize primitives, so for instance if you use jgen.writeString(..). If you use filters, that code is wrong, because the filters are stored somewhere inside of the SerializerProvider, not in the JsonGenerator. If in that case you use the jsongenerator directly, a new SerializerProvider, that doesn't know about the filters, is created internally. So instead of the shorter jgen.writeObject(o) you need to call provider.defaultSerializeValue(o, jgen). That will ensure that the filters don't get lost and can be applied.

    提交回复
    热议问题