JSON使用Java中的GSON解码带有HashMap成员的自定义类

时间:2011-03-24 19:08:48

标签: java json hashmap gson

我有以下课程:

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?或者我是否认为这一切都错了,应采取不同的方法?如果是这样我应该在哪里看?

2 个答案:

答案 0 :(得分:2)

很抱歉回答我自己的问题,但是......

确保在将JSON字符串发送到Gson之前清理空白区域。

答案 1 :(得分:1)

您使用的是什么版本的Gson?我已经在1.3,1.4,1.5和1.6上尝试了这个并且它完美地运行了