让 Jackson 使用 GSON 注释

Rag*_*age 5 java jackson gson jackson-databind

我有一个无法更改的数据模型。模型本身使用 GSON 注释进行注释。

@SerializedName("first_value")
private String firstValue = null;
Run Code Online (Sandbox Code Playgroud)

Jackson 的反序列化无法按需要进行。Jackson 无法匹配该条目,因此该值为空。

它将与

@JsonProperty("first_value")
private String firstValue = null;
Run Code Online (Sandbox Code Playgroud)

有什么方法可以让 Jackson 使用 GSON 注释,或者是否有其他解决方案不需要更改原始模型注释?

flu*_*ffy 6

我调查了一下这个问题,似乎@JsonProperty注释是用 处理的JacksonAnnotationIntrospector。扩展后者,使其成为handle @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());
    }

}
Run Code Online (Sandbox Code Playgroud)
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;

    }

}
Run Code Online (Sandbox Code Playgroud)

请注意,我不确定它的效果如何,因为我不是杰克逊专家。