杰克逊反序列化抽象类

杰克逊反序列化抽象类

本文介绍了杰克逊反序列化抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JSON ObjectMapper反序列化对象。我在尝试反序列化时看到以下错误

I am trying to deserialize an object using JSON ObjectMapper. I see the below error when trying to deserialize

我遇到了这个,用于执行多态反序列化。这基本上提供了解决上面列出的错误的解决方案。我用于反序列化的类(在本例中为OrderItem等)是jar文件的一部分。但是有一种方法可以在尝试反序列化时将JsonDeserialize定义为objectmapper的一部分,而不是向类本身添加注释,因为我无法访问它。

I came across this post for performing polymorphic deserialization. This basically provides the solution for resolving the error listed above. The classes (In this instance OrderItem etc) that I am using for deserialization are part of a jar file. However is there a way to define JsonDeserialize as part of objectmapper when trying to deserialize instead of adding annotation to the class itself as I don't have access to it.

推荐答案

是的,你可以自己编写抽象类。这个反序列化器必须确定JSON代表哪个具体类,并实例化它的一个实例。

Yes, you can write your own Custom Deserializer for the abstract class. This deserializer will have to determine which concrete class the JSON represents, and instantiate an instance of it.

这可能是更惯用的方法,但这里有一个快速和肮脏的例子:

There is likely a more idiomatic way of doing this, but here is a quick-and-dirty example:

public class Test {
    public static void main(String... args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        final SimpleModule module = new SimpleModule();
        module.addDeserializer(Animal.class, new AnimalDeserializer());
        mapper.registerModule(module);

        final String json = "{\"aGoodBoy\": true}";
        final Animal animal = mapper.readValue(json, Animal.class);
        System.out.println(animal.talk());
    }

    public static abstract class Animal {
        public abstract String talk();
    }

    public static class Fish extends Animal {
        @Override
        public String talk() {
            return "blub blub I'm a dumb fish";
        }
    }

    public static class Dog extends Animal {
        public boolean aGoodBoy;

        @Override
        public String talk() {
            return "I am a " + (aGoodBoy ? "good" : "bad") + " dog";
        }
    }

    public static class AnimalDeserializer extends StdDeserializer<Animal> {
        protected AnimalDeserializer() {
            this(null);
        }

        protected AnimalDeserializer(final Class<?> vc) {
            super(vc);
        }

        @Override
        public Animal deserialize(final JsonParser parser, final DeserializationContext context)
        throws IOException, JsonProcessingException {
            final JsonNode node = parser.getCodec().readTree(parser);
            final ObjectMapper mapper = (ObjectMapper)parser.getCodec();
            if (node.has("aGoodBoy")) {
                return mapper.treeToValue(node, Dog.class);
            } else {
                return mapper.treeToValue(node, Fish.class);
            }
        }
    }
}

这篇关于杰克逊反序列化抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:09