在Java中使用GSON与HashMap成员进行JSON解码自定义类
我有以下课程:
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之前,请确保在JSON字符串周围清除了空格。
以上是 在Java中使用GSON与HashMap成员进行JSON解码自定义类 的全部内容, 来源链接: utcz.com/qa/402901.html
