使用Jackson反序列化非字符串映射键 [英] Deserializing non-string map keys with Jackson

查看:277
本文介绍了使用Jackson反序列化非字符串映射键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张如下所示的地图:

I have a a map that looks like this:

public class VerbResult {
    @JsonProperty("similarVerbs")
    private Map<Verb, List<Verb>> similarVerbs;
}

我的动词类看起来像这样:

My verb class looks like this:

public class Verb extends Word {
    @JsonCreator
    public Verb(@JsonProperty("start") int start, @JsonProperty("length") int length,
            @JsonProperty("type") String type, @JsonProperty("value") VerbInfo value) {
        super(length, length, type, value);
    }
    //...
}

我想要序列化和反序列化我的VerbResult类的实例,但是当我这样做时,我得到这个错误:找不到类型[simple type,class my.package.Verb]

I want to serialize and deserialize instances of my VerbResult class, but when I do I get this error: Can not find a (Map) Key deserializer for type [simple type, class my.package.Verb]

我在网上看到你需要告诉杰克逊如何反序列化地图密钥,但我没有找到任何解释如何进行此操作的信息。动词类也需要在地图之外进行序列化和反序列化,因此任何解决方案都应保留此功能。

I read online that you need to tell Jackson how to deserialize map keys, but I didn't find any information explaining how to go about doing this. The verb class needs to be serialized and deserialzed outside of the map as well, so any solution should preserve this functionality.

推荐答案

建筑在这里给出的答案建议用反序列化器实现一个模块。 JodaTime Module 是一个易于理解的包含序列化器和反序列化器的模块的完整示例。

Building on the answer given here that suggests to implement a Module with a deserializer. The JodaTime Module is an easy to understand full example of a module containing serializers and deserializers.

请注意,模块功能是在Jackson 1.7版本中引入的,因此您可能需要升级。

Please note that the Module feature was introduced in Jackson version 1.7 so you might need to upgrade.

所以一步一步:


  1. 根据Joda示例为您的类创建一个包含(de)序列化程序的模块

  2. 使用 mapper.registerModule(模块)注册该模块;

  1. create a module containing a (de)serializer for your class based on the Joda example
  2. register that module with mapper.registerModule(module);

并且你将全部设定

这篇关于使用Jackson反序列化非字符串映射键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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