如何使多态杰克逊序列化与地图一起使用 [英] How to make polymorphic jackson serialization working with map

查看:71
本文介绍了如何使多态杰克逊序列化与地图一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使地图引用了我的类型,我也尝试将Jackson属性类型信息序列化.

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

通过这个简单的示例:

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));
    }
}

我得到:

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

但是我想拥有:

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

有可能吗?怎么做?

我已经尝试过enableDefaultTyping,但是我得到了:

I have tried with enableDefaultTyping but I get:

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

推荐答案

在直接序列化地图时,就像您一样,由于通用类型,对象映射器需要有关地图内容的类型信息.请参阅多态类型处理Wiki页面的第5.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)

输出:

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

这篇关于如何使多态杰克逊序列化与地图一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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