![](/img/trans.png)
[英]Jackson Polymorfic @JsonTypeInfo type attribute always null
[英]Jackson - @JsonTypeInfo property is being mapped as null?
我有這樣的回應:
{
"id":"decaa828741611e58bcffeff819cdc9f",
"statement":"question statement",
"exercise_type":"QUESTION"
}
然后,基於運動類型屬性,我想實例化不同的對象實例( ExerciseResponseDTO
子類),所以我創建了這個組合:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "exercise_type")
@JsonSubTypes({
@Type(value = ExerciseChoiceResponseDTO.class, name = "CHOICE"),
@Type(value = ExerciseQuestionResponseDTO.class, name = "QUESTION")})
public abstract class ExerciseMixIn
{}
public abstract class ExerciseResponseDTO {
private String id;
private String statement;
@JsonProperty(value = "exercise_type") private String exerciseType;
// Getters and setters
}
public class ExerciseQuestionResponseDTO
extends ExerciseResponseDTO {}
public class ExerciseChoiceResponseDTO
extends ExerciseResponseDTO {}
所以我創建我的ObjectMapper
如下
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(ExerciseResponseDTO.class, ExerciseMixIn.class);
我的測試:
ExerciseResponseDTO exercise = mapper.readValue(serviceResponse, ExerciseResponseDTO.class)
Assert.assertTrue(exercise.getClass() == ExerciseQuestionResponseDTO.class); // OK
Assert.assertEquals("decaa828741611e58bcffeff819cdc9f" exercise.getId()); // OK
Assert.assertEquals("question statement", exercise.getStatement()); // OK
Assert.assertEquals("QUESTION", exercise.getExerciseType()); // FAIL. Expected: "QUESTION", actual: null
問題是,出於某種原因,在@JsonTypeInfo
上用作屬性的運動類型屬性被映射為null 。 知道我該如何解決這個問題嗎?
最后,我在API Doc 中找到了解決方案
關於類型標識符可見性的注意事項:默認情況下,類型標識符的反序列化(在讀取 JSON 期間使用)完全由 Jackson 處理,不會傳遞給反序列化器。 但是,如果需要,可以定義屬性 visible = true 在這種情況下,屬性將在反序列化時按原樣傳遞給反序列化器(並通過 setter 或字段設置)。
所以解決方案只是簡單地添加“可見”屬性如下
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "exercise_type",
visible = true)
@JsonSubTypes({
@Type(value = ExerciseChoiceResponseDTO.class, name = "CHOICE"),
@Type(value = ExerciseQuestionResponseDTO.class, name = "QUESTION")})
public abstract class ExerciseMixIn
{}
希望這對其他人有幫助。
根據@jscherman通過設置回答, JsonTypeInfo 中的'visible' true 將有助於將運動類型作為字段訪問。
如果您也使用相同的類進行序列化,那么生成的 JSON 將出現兩次運動類型。 所以最好也更新包含到JsonTypeInfo.As.EXISTING_PROPERTY
並且還值得查看包含的所有其他選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.