使用jackson反序列化为自定义对象的HashMap

wbj*_*wbj 47 java jackson json-deserialization

我有以下课程:

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
}
Run Code Online (Sandbox Code Playgroud)

当我执行以下代码时:

    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(); 
    }
Run Code Online (Sandbox Code Playgroud)

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

{
  "theme2": {
    "themeName": "theme2",
    "customized": true,
    "descriptor": {
      "foo": "one",
       "bar": "two"
    }
  },
  "theme1": {
    "themeName": "theme1",
    "customized": false,
    "descriptor": null
  }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是让上面的json字符串去反序列化

HashMap<String, Theme> 
Run Code Online (Sandbox Code Playgroud)

宾语.

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

HashMap<String, Themes> themes =
        objectMapperFactory.createObjectMapper().readValue(json, HashMap.class);
Run Code Online (Sandbox Code Playgroud)

使用正确的密钥将其反序列化为HashMap,但不为值创建Theme对象.我不知道在readValue()方法中指定什么而不是"HashMap.class".

任何帮助,将不胜感激.

Mic*_*ber 85

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

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


小智 17

您可以使用TypeReference类,该类使用用户定义的类型对map执行类型转换.有关http://wiki.fasterxml.com/JacksonInFiveMinutes的更多文档

ObjectMapper mapper = new ObjectMapper();
Map<String,Theme> result =
  mapper.readValue(src, new TypeReference<Map<String,Theme>>() {});
Run Code Online (Sandbox Code Playgroud)