java - 使用 Jackson 反序列化为自定义对象的 HashMap

标签 java jackson json-deserialization

我有以下类(class):

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 字符串如下所示:

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

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

HashMap<String, Theme> 

对象。

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

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

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

如有任何帮助,我们将不胜感激。

最佳答案

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

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

关于java - 使用 Jackson 反序列化为自定义对象的 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57727538/

相关文章:

java - 如何获取字符串中第一个和最后一个字符的索引?

java - 使用实例化的集合类型进行 jackson 反序列化而不是初始化一个新的集合类型?

java - 无法构造 - Jackson 的实例

java - 使用 Jackson 解码和反序列化其值为 Base64 编码、字符串化 JSON blob 的字段的最简单方法

java - 使用继承的自定义 JsonDeserializer 导致 StackOverflowError

java - 像在 Eclipse 中一样在 IntelliJ IDEA 中更改 Ctrl+Shift+Left/Right 的行为

java - 将表单数据作为文件发布请求 (wsdl.xml)

java - 使用 JRE 7 或 JRE 8 创建 dll 的过程

java - 创建通用的 ObjectMapper 方法以跨多个 POJO 类进行反序列化

c# - 如何使用合约解析器和值提供者在反序列化过程中自定义值设置