使用 jackson 反序列化为自定义对象的 HashMap [英] Deserializing into a HashMap of custom objects with jackson

查看:49
本文介绍了使用 jackson 反序列化为自定义对象的 HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

import java.io.Serializable;
import java.util.HashMap;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Theme implements Serializable {

    @JsonProperty
    private String themeName;

    @JsonProperty
    private boolean customized;

    @JsonProperty
    private HashMap<String, String> descriptor;

    //...getters and setters for the above properties
}

当我执行以下代码时:

    HashMap<String, Theme> test = new HashMap<String, Theme>();
    Theme t1 = new Theme();
    t1.setCustomized(false);
    t1.setThemeName("theme1");
    test.put("theme1", t1);

    Theme t2 = new Theme();
    t2.setCustomized(true);
    t2.setThemeName("theme2");
    t2.setDescriptor(new HashMap<String, String>());
    t2.getDescriptor().put("foo", "one");
    t2.getDescriptor().put("bar", "two");
    test.put("theme2", t2);
    String json = "";
    ObjectMapper mapper = objectMapperFactory.createObjectMapper();
    try {
        json = mapper.writeValueAsString(test);
    } catch (IOException e) {
        e.printStackTrace(); 
    }

生成的json字符串如下所示:

The json string produced looks like this:

{
  "theme2": {
    "themeName": "theme2",
    "customized": true,
    "descriptor": {
      "foo": "one",
       "bar": "two"
    }
  },
  "theme1": {
    "themeName": "theme1",
    "customized": false,
    "descriptor": null
  }
}

我的问题是将上面的 json 字符串反序列化为一个

My problem is getting the above json string to de-serizlize back into a

HashMap<String, Theme> 

对象.

我的反序列化代码如下所示:

My de-serialization code looks like this:

HashMap<String, Themes> themes =
        objectMapperFactory.createObjectMapper().readValue(json, HashMap.class);

使用正确的键反序列化为 HashMap,但不为值创建 Theme 对象.我不知道在 readValue() 方法中指定什么来代替HashMap.class".

Which de-serializes into a HashMap with the correct keys, but does not create Theme objects for the values. I don't know what to specify instead of "HashMap.class" in the readValue() method.

任何帮助将不胜感激.

推荐答案

您应该创建特定的 Map 类型并将其提供给反序列化过程:

You should create specific Map type and provide it into deserialization process:

TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Theme.class);
HashMap<String, Theme> map = mapper.readValue(json, mapType);

这篇关于使用 jackson 反序列化为自定义对象的 HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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