JSON在Java中使用GSON解码具有HashMap成员的自定义类
我有以下课程:
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?还是我的做法完全错误,应该采取不同的方法?如果是的话,我应该去哪里看强>
# 1 楼答案
很抱歉回答我自己的问题,但是
在将JSON字符串发送到Gson之前,请确保已清除JSON字符串周围的空白
# 2 楼答案
您使用的是什么版本的Gson?我在1.3、1.4、1.5和1.6上试过,效果非常好