使用Jackson的@JsonTypeInfo和自定义序列化程序 [英] Using Jackson's @JsonTypeInfo with a custom serializer

查看:644
本文介绍了使用Jackson的@JsonTypeInfo和自定义序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用自定义序列化程序时,我遇到了Jackson的问题,它不遵守 @JsonTypeInfo 注释。下面的简化示例不需要自定义序列化,并在不使用自定义序列化程序时按预期输出类型属性。但是,一旦启用了自定义序列化程序,就不会写入类型属性并阻止反序列化。这是我的实际系统的测试用例,它需要一个自定义序列化程序,如果它有所不同,则试图序列化 Map< Enum,Map< Enum,T>> 其中 T 是未写入类型信息的多态类。如何编写自定义序列化程序以正确处理类型信息?我希望如果我能在下面的测试用例中使用它,我将能够将相同的概念应用于实际代码。

I'm running into a problem with Jackson where it does not respect the @JsonTypeInfo annotations when I use a custom serializer. The simplified example below does not require the custom serialization and outputs the type property as expected when I don't use the custom serializer. However, once the custom serializer has been enabled, the type property is not written and prevents deserialization. This is a test case for my actual system, which does require a custom serializer and, if it makes a difference, is attempting to serialize a Map<Enum, Map<Enum, T>> where T is the polymorphic class whose type information is not being written. How can I write the custom serializer so it correctly handles the type information? I'm hoping that if I can get it working for the test case below, I will be able to apply the same concepts to the actual code.

测试程序尝试尽可能地模拟我在实际应用程序中使用的序列化过程,构建 Map<> 并序列化而不是序列化动物园直接。

The test program attempts to simulate as closely as possible the serialization process I'm using in the real application, building a Map<> and serializing that instead of serializing the Zoo directly.

预期输出:

{
    "Spike": {
        "type": "dog",
        "name": "Spike",
        "breed": "mutt",
        "leashColor": "red"
    },
    "Fluffy": {
        "type": "cat",
        "name": "Fluffy",
        "favoriteToy": "spider ring"
    }
}

按在 SimpleModule 中注释掉自定义序列化程序注册,您可以看到输出的类型信息,但是在注册了序列化程序的情况下,输出如上所示,但没有输入道具erty。

By commenting out the custom serializer registration in the SimpleModule you can see the type information is output, but with the serializer registered, the output is as above but without the type property.

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonSubTypes.Type;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.annotate.JsonTypeInfo.As;
import org.codehaus.jackson.annotate.JsonTypeInfo.Id;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.Module;
import org.codehaus.jackson.map.Module.SetupContext;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ResolvableSerializer;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.module.SimpleModule;
import org.codehaus.jackson.map.module.SimpleSerializers;

public class JacksonTest {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Module m = new SimpleModule("TestModule", new Version(1,0,0,"")) {
            @Override
            public void setupModule(SetupContext context) {
                super.setupModule(context);
                context.setMixInAnnotations(Animal.class, AnimalMixIn.class);

                SimpleSerializers serializers = new SimpleSerializers();
                serializers.addSerializer(Zoo.class, new ZooSerializer());
                context.addSerializers(serializers);
            }
        };
        mapper.registerModule(m);
        mapper.configure(Feature.INDENT_OUTPUT, true);

        Zoo zoo = new Zoo();
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(new Dog("Spike", "mutt", "red"));
        animals.add(new Cat("Fluffy", "spider ring"));
        zoo.animals = animals;

        System.out.println(zoo);
        String json = mapper.writeValueAsString(zoo);
        System.out.println(json);
    }

    static class Zoo {
        public Collection<Animal> animals = Collections.EMPTY_SET;

        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("Zoo: { ");
            for (Animal animal : animals)
                sb.append(animal.toString()).append(" , ");
            return sb.toString();
        }
    }

    static class ZooSerializer extends JsonSerializer<Zoo> {
        @Override
        public void serialize(Zoo t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
            Map<Object, Animal> animalMap = new HashMap<Object, Animal>();
            for (Animal a : t.animals)
                animalMap.put(a.getName(), a);
            jg.writeObject(animalMap);
        }
    }

    @JsonTypeInfo(
            use=Id.NAME,
            include=As.PROPERTY,
            property="type")
    @JsonSubTypes({
        @Type(value=Cat.class,name="cat"),
        @Type(value=Dog.class,name="dog")
    })
    static abstract class AnimalMixIn {
    }

    static interface Animal<T> {
        T getName();
    }

    static abstract class AbstractAnimal<T> implements Animal<T> {
        private final T name;

        protected AbstractAnimal(T name) {
            this.name = name;
        }

        public T getName() {
            return name;
        }
    }

    static class Dog extends AbstractAnimal<String> {
        private final String breed;
        private final String leashColor;

        @JsonCreator
        public Dog(@JsonProperty("name") String name, @JsonProperty("breed") String breed,
                   @JsonProperty("leashColor") String leashColor)
        {
            super(name);
            this.breed = breed;
            this.leashColor = leashColor;
        }

        public String getBreed() {
            return breed;
        }

        public String getLeashColor() {
            return leashColor;
        }

        @Override
        public String toString() {
            return "Dog{" + "name=" + getName() + ", breed=" + breed + ", leashColor=" + leashColor + "}";
        }
    }

    static class Cat extends AbstractAnimal<String> {
        private final String favoriteToy;

        @JsonCreator
        public Cat(@JsonProperty("name") String name, @JsonProperty("favoriteToy") String favoriteToy) {
            super(name);
            this.favoriteToy = favoriteToy;
        }

        public String getFavoriteToy() {
            return favoriteToy;
        }

        @Override
        public String toString() {
            return "Cat{" + "name=" + getName() + ", favoriteToy=" + favoriteToy + '}';
        }
    }
}



编辑:添加其他测试用例这可能会澄清问题



在阅读了有关类似问题的更多问题后,我决定尝试修改自定义序列化程序以缩小问题所在。我发现将 Animal 对象添加到任何通用类型的集合(列表< Animal> 映射< Object,Animal> 已经过测试),类型信息未被序列化。但是,在序列化 Animal [] 时,包含了类型信息。不幸的是,虽然我可以在测试代码中改变这种行为,但我需要生成代码来序列化具有多态值的 Map

Adding additional test cases that may clarify the problem

After reading some more questions about similar issues, I decided to try modifying my custom serializer to narrow down where the problem is. I discovered that adding my Animal objects to any generically typed Collection (List<Animal> and Map<Object, Animal> were tested), the type information was not serialized. However, when serializing an Animal[], the type information was included. Unfortunately, while I can vary that behavior in the test code, I need my production code to serialize a Map with polymorphic values.

将自定义 ZooSerializer.serialize()方法更改为以下输出类型信息,但丢失了 Map 我需要的语义:

Changing the custom ZooSerializer.serialize() method to the following does output type information, but loses the Map semantics I need:

public void serialize(...) {
    Animal[] animals = t.animals.toArray(new Animal[0]);
    jg.writeObject(animals);
}


推荐答案

我找到了解决办法,或者这可能是合适的解决方案。无论哪种方式,它似乎都有效。如果有更好的方法,请告诉我。 (我觉得应该有)

I found a work-around, or maybe this is the appropriate solution. Either way, it appears to be working. Please let me know if there is a better way. (I feel like there should be)

我定义了一个实现 Map< Object,Animal> 的内部类为 JsonGenerator.writeObject()提供了该类的实例,而不是提供 Map 。一旦通用声明被隐藏,Jackson似乎能够解析键和值类型,并为创建的 MapSerializer提供非null TypeSerializer ,产生所需的JSON输出。

I defined an internal class that implements Map<Object, Animal> and provided an instance of that class to JsonGenerator.writeObject() instead of providing it a Map. Jackson seems to be able to resolve the key and value types once the generic declarations are "hidden" and provides a non-null TypeSerializer to the created MapSerializer, resulting in the desired JSON output.

以下对测试源代码的添加/修改会生成所需的输出。

The following additions/modifications to the test source code generate the desired output.

private static class AnimalMap implements Map<Object, Animal> {
    private final Map<Object, Animal> map;

    public AnimalMap() {
        super();
        this.map = new HashMap<Object, Animal>();
    }

    // omitting delegation of all Map<> interface methods to this.map
}

static class ZooSerializer extends SerializerBase<Zoo> {
    public ZooSerializer() {
        super(Zoo.class);
    }

    @Override
    public void serialize(Zoo t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessing Exception {
        AnimalMap animals = new AnimalMap();
        for (Animal a : t.animals)
            animals.put(a.getName(), a);
        jg.writeObject(animals);
    }
}

这篇关于使用Jackson的@JsonTypeInfo和自定义序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆