简体   繁体   English

如何使多态杰克逊序列化与地图一起使用

[英]How to make polymorphic jackson serialization working with map

I try to have Jackson property type info serialized, even when my type is referenced by a map. 我尝试将Jackson属性类型信息序列化,即使地图引用了我的类型。

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: 我已经尝试过enableDefaultTyping但我得到:

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

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 . 请参考“ 多态类型处理”维基页面的第5.1章。

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"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM