Jackson JSON library: how to instantiate a class that contains abstract fields

后端 未结 4 701
你的背包
你的背包 2020-11-30 05:20

I want to convert a JSON string into java object, but the class of this object contains abstract fields, which Jackson can\'t instantiate, and doesn\'t produce the object. W

4条回答
  •  眼角桃花
    2020-11-30 06:10

    If you want to pollute neither your JSON with extra fields nor your classes with annotation, you can write a very simple module and deserializer that uses the default subclass you want. It is more than one line due to some boilerplate code, but it is still relatively simple.

    class AnimalDeserializer extends StdDeserializer {
        public AnimalDeserializer() {
            super(Animal.class);
        }
    
        public Animal deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
            return jsonParser.readValueAs(Cat.class);
        }
    }
    
    class AnimalModule extends SimpleModule {
        {
            addDeserializer(Animal.class, new AnimalDeserializer());
        }
    }
    

    Then register this module for the ObjectMapper and that's it (Zoo is the container class that has an Animal field).

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new AnimalModule());
    return objectMapper.readValue(json, Zoo.class);
    

提交回复
热议问题