自定义反序列化多态对象

时间:2019-06-07 05:51:37

标签: java json jackson

说我具有以下结构,已将其序列化为JSON。

public abstract class Vehicles {
    String make;
    String model;
    Map<Parts, int> partsList = new HashMap<>; // a list of parts for the vehicle and how much each part costs

    // Getters, setters, etc.
}

public class Cars extends Vehicles {
    int seats;

    // Getters, setters, etc.
}

public class Trucks extends Vehicles {
    int cargo;

    // Getters, setters, etc.
}

然后,我需要一个可以处理partsList的自定义反序列化器,每次对具体的子类进行反序列化时都将重用该序列化器。我已经看到一些问题,描述了如何为子类调用自定义反序列化器。我似乎找不到能够允许对超类中创建的属性进行反序列化的解决方案,从而避免在每个子子类中重复反序列化代码。

public class VehicleDeserializer extends StdDeserializer<Vehicles> {
    protected VehicleDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Vehicle deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);

        TypeReference<Map<Parts, int>> typeReference = new TypeReference() {};
        Map<Parts, int> parts = objectMapper.readValue(jsonNode.get("partsList").asText(), typeReference) // somehow need to feed this to partsList map when each subclass is deserialized -- THIS IS THE BIT I DON'T KNOW HOW TO DO.

        // code to call the appropriate subclass deserializer -- I don't need help with this bit...yet.
}

编辑:为澄清起见,我认为有很多示例说明了如何调用适当的子类反序列化器。我要做的是避免在每个子类反序列化器中使用重复的代码来处理超类中的地图。

0 个答案:

没有答案