jackson – @JsonTypeInfo属性被映射为null?
我正在处理这个问题。 假设我有这样的回答:
{ "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 。 知道如何解决这个问题吗?
最后,我在API Doc中找到了解决方案
关于类型标识符的可见性的注意事项:默认情况下,类型标识符的反序列化(在读取JSON期间使用)完全由Jackson处理,并且不会传递给反序列化器。 但是,如果需要,可以定义属性visible = true,在这种情况下,属性将在反序列化时按原样传递给反序列化器(并通过setter或field设置)。
所以解决方案只是添加’ visible ‘属性,如下所示
@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将有助于将exercise_type作为字段进行访问。
如果您使用相同的类进行序列化,那么生成的JSON将使exercise_type出现两次。 因此最好还将include更新为JsonTypeInfo.As.EXISTING_PROPERTY
并且还值得查看包含的所有其他选项 。
- 如何使用jackson遍历生成的json模式并将自定义属性放在json模式中
- 将Jackson ObjectMapper类设置为不使用双重科学记数法
- java.lang.ClassNotFoundException:com.fasterxml.jackson.annotation.JsonInclude $ Value
- jacksonJSON字段映射大写?
- 忽略“无法从START_ARRAY令牌中反序列化java.util.LinkedHashMap的实例”错误
- jackson:自定义集合序列化到JSON
- 如何在不重写serialize方法的情况下覆盖特定类的JsonSerializer的isEmpty方法?
- jackson使用spring接口列表反序列化对象
- Jackson序列化:将字段值设置为XML元素名称