【发布时间】:2011-07-22 09:49:09
【问题描述】:
我有以下课程:
class IndexItem {
private String word;
private HashMap<String, Integer> docs;
private Integer total;
public IndexItem(String word) {
this.total = 0;
this.docs = new HashMap<String, Integer>();
this.word = word;
}
public IndexItem() {
this.total = 0;
this.docs = new HashMap<String, Integer>();
this.word = "";
}
}
我还使用 GSON 从此类实例之一编码以下 JSON 字符串:
{"word":"refer","docs":{"c84ada58bb47e7ee8fab14d6d0ae1978.html":7,"7664010c28b7366813f52b30fd683f43.html":6,"a51ed147e16ea44244d7362367caeb4e.html":2},"total":15}
我尝试运行以下命令来解码此字符串:
IndexItem item = new Gson().fromJson(jsonStr, IndexItem.class);
当我尝试运行它时,我收到以下错误消息:
Exception in thread "main" com.google.gson.JsonParseException:
The JsonDeserializer MapTypeAdapter failed to deserialized
json object
{"c84ada58bb47e7ee8fab14d6d0ae1978.html":7,"7664010c28b7366813f52b30fd683f43.html":6,"a51ed147e16ea44244d7362367caeb4e.html":2}
given the type class java.util.HashMap
at
com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDeserializerExceptionWrapper.java:63)
at
com.google.gson.JsonDeserializationVisitor.invokeCustomDeserializer(JsonDeserializationVisitor.java:88)
at
com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler(JsonObjectDeserializationVisitor.java:116)
我是 GSON 新手,很长时间没有接触过 Java。所以我的问题是:
有没有办法让 GSON 解码我班级中的 HashMap?或者我是否将这一切都错了,应该采取不同的方法?如果是,我应该去哪里看?
【问题讨论】: