Jackson - 包括地图键的 JsonTypeInfo

Jackson - include JsonTypeInfo for Map keys

在 Java 中,我需要序列化一个对象,该对象是 Map<Object, Object> 的包装器。我想在生成的 Json 中包含一个 class 类型信息,我可以通过 @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) 来完成。但是,类型信息仅包含在映射值中,不包含键。

例如:

@Data
public class FunnyObject {

    @JsonProperty(value = "fields")
    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
    private Map<Object, Object> fields = new HashMap<>();
}

正在初始化:

Map<Object, Object> fields = new HashMap<>();
fields.put("Date", new Date());
fields.put(new Date(), "ups");
fields.put(MyTypes.TYPE_B, "Reversed");

FunnyObject funnyObject = new FunnyObject();
funnyObject.setFields(fields);

MyTypes 枚举:

public enum MyTypes {
    TYPE_A("hello"),
    TYPE_B("World");

    private String txt;

    MyTypes(String txt) {
        this.txt = txt;
    }
}

生成的 Json 是这样的,其中 class 类型信息仅包含在值中。 我怎么能把这个也包括在密钥中?

{
    "fields": {
        "2021-01-25T13:28:18.718+00:00": "ups",
        "TYPE_B": "Reversed",
        "Date": [
            "java.util.Date",
            1611581298718
        ]
    }
}

我想 Michał Ziober 在对我原来的 post

的评论中回答了这个问题

"JSON 键始终是字符串"