杰克逊的BeanDeserializerModifier不适用于最终字段

时间:2019-01-08 06:24:45

标签: java json jackson annotations lombok

我写了一个Custom Serializer和Custom Deserializer来序列化带有@Confidential注释的属性。

@Data
public class Person {
   private String name;

   @Confidential
   private String address;
}

自定义序列化程序使用以下值序列化POJO:

{ "name": "John Doe", "address": "Kearney St"}

如下:

{"name":"John Doe", "address": {"value":"IjIwMzEwIDU4dGggTG4gTkUi"}}

自定义反序列化器还可以将JSON反序列化为Person POJO fine。

但是,当我将Person POJO中的字段设置为最终时,序列化继续起作用,但反序列化失败。

@Data
public class Person {
    private final String name;

    @Confidential
    private final String address;
 }

这是BeanSerializerModifier的实现:

@AllArgsConstructor
public class CustomDeserializerModifier extends BeanDeserializerModifier {
    private final ObjectMapper objectMapper;

    @Override
    public BeanDeserializerBuilder updateBuilder(final DeserializationConfig config,
                                                 final BeanDescription beanDesc,
                                                 final BeanDeserializerBuilder builder) {
        Iterator<SettableBeanProperty> beanPropertyIterator = builder.getProperties();
        beanPropertyIterator.forEachRemaining(settableBeanProperty -> {
            final Confidential annotation = settableBeanProperty.getAnnotation(Confidential.class);
            if (encryptedProperty != null) {
                JsonDeserializer<Object> current = settableBeanProperty.getValueDeserializer();
                final SettableBeanProperty newSettableBeanProperty =
                        settableBeanProperty.withValueDeserializer(
                                new CustomDeserializer(annotation, current, objectMapper)
                        );
                builder.addOrReplaceProperty(newSettableBeanProperty, true);
            }
        });

        return builder;
    }
}

我发现,Person POJO字段为final时,从未调用CustomDeserializer。

这是错误消息:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: {"name":"John Doe","address":{"value":"IjIwMzEwIDU4dGggTG4gTkUi"}}; line: 1, column: 30] (through reference chain: com.custom.model.Person["address"])

杰克逊专家能否告诉我为什么POJO字段为final时为什么我的CustomDeserializer不能被调用。

谢谢!

0 个答案:

没有答案