3

我有自己的自定义反序列化器

@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它是一个基类,并且地图应该有地图字符串,汽车的子类)

输入 JSON = [{"name": "honda", "type": "Regular , "speed": 60}]

这应该在地图中,例如Map.put("honda", RegularCar.class)

4

1 回答 1

2

您可以根据JSON 中字段Car的值对基类进行注释,以告诉 Jackson 要实例化哪些子类。"type"例如,如果您拥有RegularCarClassicCar扩展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);

whereCar car实际上指向一个RegularCar实例。由于容器被声明为Map<String, Car<?, ?>> CarsMap这正是您想要的put,然后适当地getMap.

于 2017-11-26T17:29:12.773 回答