我有自己的自定义反序列化器
@Override
public Map<String, Car<?, ?>> deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode carsNode = p.getCodec().readTree(p);
Map<String, Car<?, ?>> CarsMap = new HashMap<String, Car<?, ?>>();
ObjectMapper mapper = new ObjectMapper();
for (JsonNode node : carsNode) {
CarsMap.put(node.get("name").asText(), mapper.readValue(node.asText(), Car.class));
}
return CarsMap;
}
认为这不起作用,因为Car
是基类,地图应该有Map String,SubClasses of Cars
输入JSON = [{&#34; name&#34;:&#34; honda&#34;,&#34; type&#34;:&#34; Regular,&#34; speed&#34;: 60}]
这应该在地图中,例如Map.put("honda", RegularCar.class)
答案 0 :(得分:2)
您可以注释基类Car
类,以告诉Jackson根据JSON中"type"
字段的值实例化哪些子类。例如,如果RegularCar
和ClassicCar
延长Car
。
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = RegularCar.class, name = "Regular"),
@JsonSubTypes.Type(value = ClassicCar.class, name = "Classic")
})
class Car {
这将允许您像这样解析:
String json = "{\"name\": \"honda\", \"type\": \"Regular , \"speed\": 60}";
Car car = mapper.readValue(json, Car.class);
其中Car car
实际上指向RegularCar
个实例。由于容器被声明为Map<String, Car<?, ?>> CarsMap
,因此这正是您想要put
的所有内容,然后从get
中适当地投射Map
。{/ p>