1
我有几个的Json字符串如下:杰克逊多态性 - 抽象类,没有财产
{"type1": {"name": "Arnold"}}
{"type2": {"id": "abcd", "job": "plumber"}}
我想是一个JSON字符串转换为根据Type1
或Type2
类之一,最终的事元素的root属性:
// Type0 abstract class
public abstract class Type0 {
}
// Type1 class.. convert to it if {"type1": {...}}
@JsonRootName(value = "type1")
public class Type1 extends Type0 {
@JsonProperty("name")
String name;
}
// Type2 class.. convert to it if {"type2": {...}}
@JsonRootName(value = "type2")
public class Type2 extends Type0 {
@JsonProperty("id")
String id;
@JsonProperty("job")
String job;
}
如何配置杰克逊的ObjectMapper
,这样我可以做到这一点反序列化?我认为一个逻辑的像如下,它是可行的:
ObjectMapper mapper = new ObjectMapper();
result = mapper.readValue(jsonString, Type0.class);
//TODO: code for deciding whether result is Type1 or Type2 and casting to it