[英]Make Jackson use GSON Annotations
我有一個無法更改的數據 model。 model 本身帶有 GSON 注釋。
@SerializedName("first_value")
private String firstValue = null;
Jackson 的反序列化無法按需工作。 Jackson 無法匹配條目,因此值為 null。
它會與
@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;
}
}
請注意,我不確定它的效果如何,因為我不是 Jackson 專家。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.