JSON Decode Custom Class with HashMap member using GSON in Java

…衆ロ難τιáo~ 提交于 2019-12-31 01:52:27

问题


I have the following class:

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 = "";
    }
}

I also have the following JSON string encoded from one of this classes instances using GSON:

{"word":"refer","docs":{"c84ada58bb47e7ee8fab14d6d0ae1978.html":7,"7664010c28b7366813f52b30fd683f43.html":6,"a51ed147e16ea44244d7362367caeb4e.html":2},"total":15}

I tried running the following command to decode this string:

IndexItem item = new Gson().fromJson(jsonStr, IndexItem.class);

And I get the following error message when I try running it:

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)

I am new to GSON and haven't dealt with Java in a long time. So my question is:

Is there a way to get GSON to decode the HashMap in my class? OR am I going about this all wrong and should take a different approach? If so where should I look?


回答1:


Sorry to answer my own question, but...

Make sure the white space is cleaned up around your JSON string before sending it to Gson.




回答2:


What version of Gson are you using? I've tried this on 1.3, 1.4, 1.5 and 1.6 and it worked perfectly



来源:https://stackoverflow.com/questions/5424263/json-decode-custom-class-with-hashmap-member-using-gson-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!