杰克逊使用吸气剂反序列化字段

时间:2020-03-22 18:47:58

标签: java json jackson

我让杰克逊这样设置。

objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

这样,它仅序列化带有@JsonProperty注释的字段和函数,这正是我想要的。但是,它使用java.lang.reflect.Field.get(bean)来获取字段的值。

如果我可以让Jackson使用吸气剂访问字段值,我会更喜欢。

有什么办法可以做到这一点?

更新

我调试了一下,发现了

   public void serializeAsField(Object bean, JsonGenerator gen,
            SerializerProvider prov) throws Exception {
        // inlined 'get()'
        final Object value = (_accessorMethod == null) ? _field.get(bean)
                : _accessorMethod.invoke(bean, (Object[]) null);
BeanPropertyWriter

_accessorMethod为空。

更新2

这是我要序列化的类之一。

import lombok.Data;

@Data
public class JwtAuthenticationResponse{
    private final String token;
}

使用lombok的@Data注释生成Getter。

更新3

我进一步调试并得到一个POJOPropertiesCollector._removeUnwantedAccessor(props)

它删除了先前找到的访问器,因为它的可见性已由objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);定义。

由于我正在使用lombok,因此无法在getter上使用任何@Json ***批注。这就是为什么我决定只使用字段来确定将要序列化的属性的原因。但是我一直想使用它们适当的获取器作为值访问器。

有什么办法吗?

0 个答案:

没有答案