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

后端 未结 4 688
你的背包
你的背包 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 05:59

    A full fledged answer with a very clear example can be found here: https://stackoverflow.com/a/30386694/584947

    Jackson refers to this as Polymorphic Deserialization.

    It definitely helped me with my issue. I had an abstract class that I was saving in a database and needed to unmarshal it to a concrete instance of a class (understandably).

    It will show you how to properly annotate the parent abstract class and how to teach jackson how to pick among the available sub-class candidates at run-time when unmarshaling.

    0 讨论(0)
  • 2020-11-30 06:00

    the problem can solve with the annotation @JsonDeserialize on the abstract class refers to Jackson Exceptions Problems and Solutions https://www.baeldung.com/jackson-exception

    0 讨论(0)
  • 2020-11-30 06:01

    There are multiple ways; before version 1.8, simplest way is probably to do:

    @JsonDeserialize(as=Cat.class)
    public abstract class AbstractAnimal { ... }
    

    as to deciding based on attribute, that is best done using @JsonTypeInfo, which does automatic embeddeding (when writing) and use of type information.

    There are multiple kinds of type info (class name, logical type name), as well as inclusion mechanisms (as-included-property, as-wrapper-array, as-wrapper-object). This page: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization explains some of the concepts.

    0 讨论(0)
  • 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<Animal> {
        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);
    
    0 讨论(0)
提交回复
热议问题