我有一个无法更改的数据模型.

@SerializedName("first_value")
private String firstValue = null;

与杰克逊的反序列化没有按需要进行.Jackson无法匹配条目,因此该值为空.

它可以与

@JsonProperty("first_value")
private String firstValue = null;

我有没有办法让Jackson使用GSON注释,或者有没有其他解决方案不需要更改原始模型注释?

推荐答案

我研究了一下这个问题,似乎@JsonProperty注释是用JacksonAnnotationIntrospector处理的.扩展后者,使其成为句柄@SerializedName,似乎可以保持原始行为(我希望如此):

@NoArgsConstructor(access = AccessLevel.PRIVATE)
final class SerializedNameAnnotationIntrospector
        extends JacksonAnnotationIntrospector {

    @Getter
    private static final AnnotationIntrospector instance = new SerializedNameAnnotationIntrospector();

    @Override
    public PropertyName findNameForDeserialization(final Annotated annotated) {
        @Nullable
        final SerializedName serializedName = annotated.getAnnotation(SerializedName.class);
        if ( serializedName == null ) {
            return super.findNameForDeserialization(annotated);
        }
        // TODO how to handle serializedName.alternate()?
        return new PropertyName(serializedName.value());
    }

}
public final class SerializedNameAnnotationIntrospectorTest {

    private static final AnnotationIntrospector unit = SerializedNameAnnotationIntrospector.getInstance();

    @Test
    public void test()
            throws IOException {
        final ObjectMapper objectMapper = new ObjectMapper()
                .setAnnotationIntrospector(unit);
        final Model model = objectMapper.readValue("{\"first_value\":\"foo\",\"second_value\":\"bar\"}", Model.class);
        Assertions.assertEquals("foo", model.firstValue);
        Assertions.assertEquals("bar", model.secondValue);
    }

    private static final class Model {

        @SerializedName("first_value")
        private final String firstValue = null;

        // does not exist in the original model,
        // but retains here to verify whether the introspector still works fine
        @JsonProperty("second_value")
        private final String secondValue = null;

    }

}

请注意,我不确定它有多好,因为我不是杰克逊的专家.

Java相关问答推荐

内容处置 destruct 了PSP请求

Java Swing绘制gif作为多个JSYS和JLabels的背景

将@ManyToOne JPA Composite Key用作Id保存实体添加额外参数

Java Streams在矩阵遍历中的性能影响

在现代操作系统/硬件上按块访问数据值得吗?

neo4j java驱动程序是否会在错误发生时自动回滚事务?

根据对象和值的参数将映射<;T、值&>转换为列表<;T&>

解析Javadoc时链接的全限定类名

如何使用Maven和Spring Boot将构建时初始化、跟踪类初始化正确传递到本机编译

使用传递的参数构造异常的Mockito-doThrow(或thenThrow)

Jolt变换JSON数组问题

声明MessageChannel Bean的首选方式

如何在一行中使用Dijkstra中的Java Stream

Regex以查找不包含捕获组的行

Java.lang.invke.LambdaConversionException:实例方法InvokeVirtual的参数数量不正确

带有可选部分的Java DateTimeForMatter

活泼的一次判断成语,结果中等

Java方法参数:括号中的类型声明?

为什么Java编译器为没有参数的方法(getter方法)创建桥接方法

关于正则表达式的一个特定问题,该问题与固定宽度负向后看有关