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

我有以下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(); } 

生成的jsonstring如下所示:

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

我的问题是让上面的jsonstring去serizlize回到一个

 HashMap<String, Theme> 

目的。

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

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

其中用正确的键反序列化成一个HashMap,但不创build值的主题对象。 我不知道要在readValue()方法中指定什么,而不是“HashMap.class”。

任何帮助,将不胜感激。

您应该创build特定的Maptypes并将其提供到反序列化过程中:

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

您可以使用TypeReference类,它使用用户定义的types为映射执行types转换。 更多文档在http://wiki.fasterxml.com/JacksonInFiveMinutes

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