![](/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.