我有这样的回应:
{
"id":"decaa828741611e58bcffeff819cdc9f",
"statement":"question statement",
"exercise_type":"QUESTION"
}
然后,根据exercise_type属性,我想实例化不同的对象实例(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
上用作属性的exercise_type属性被映射为null。你知道我该怎么解决这个问题吗?
发布于 2018-10-04 14:28:24
根据@jscherman answer的设置,JsonTypeInfo中的'visible‘true将有助于将exercise_type作为字段访问。
如果您使用相同的类来序列化,那么产生的JSON将使exercise_type出现两次。因此最好也将include更新为JsonTypeInfo.As.EXISTING_PROPERTY
同样值得关注的是all other options的include。
https://stackoverflow.com/questions/33611199
复制相似问题