How to make polymorphic jackson serialization working with map

谁说我不能喝 提交于 2021-02-07 10:24:36

问题


I try to have Jackson property type info serialized, even when my type is referenced by a map.

With this simple sample:

import java.util.HashMap;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DemoJackson {
    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
    public static abstract class Animal {}

    @JsonTypeName("cat")
    public static class Cat extends Animal {}

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        Cat cat = new Cat();
        System.out.println(objectMapper.writeValueAsString(cat));

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("data", cat);

        System.out.println(objectMapper.writeValueAsString(map));
    }
}

I get:

{"@type":"cat"}
{"data":{}}

But I would like to have:

{"@type":"cat"}
{"data":{"@type":"cat"}}

Is it possible? How to do it?

I have tried with enableDefaultTyping but I get:

{"@type":"cat"}
{"data":["DemoJackson$Cat",{}]}

回答1:


When you are serializing a map directly, as you do, the object mapper needs the type information about the map contents because of generic typing. Please refer to chapter 5.1 of Polymorphic Type Handling wiki page.

An example of passing the type reference information when serializing the map of Animals.

objectMapper.writerWithType(new TypeReference<Map<String, Animal>>() {})
    .writeValueAsString(map)

Output:

{"@type":"cat"}
{"data":{"@type":"cat"}}


来源:https://stackoverflow.com/questions/23172718/how-to-make-polymorphic-jackson-serialization-working-with-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!