【问题标题】:JSON Decode Custom Class with HashMap member using GSON in Java在 Java 中使用 GSON 对带有 HashMap 成员的 JSON 解码自定义类
【发布时间】: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?或者我是否将这一切都错了,应该采取不同的方法?如果是,我应该去哪里看?

【问题讨论】:

    标签: java json hashmap gson


    【解决方案1】:

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

    确保在将 JSON 字符串发送到 Gson 之前清除其周围的空白。

    【讨论】:

    • 嗯?常规空格对于 JSON 来说并不重要,所以这无关紧要。但是你那里有一些控制字符之类的吗?
    • 我知道很奇怪,但是字符串末尾的换行符使 GSON 失败。
    • 好的。可能要考虑提交错误报告;这将有助于项目团队解决问题,因为这听起来像一个错误
    • 对于我们这些也是新手的人,我们将不胜感激您如何“清理”空白/换行符。不错的帖子,谢谢。
    【解决方案2】:

    您使用的是什么版本的 Gson?我在 1.3、1.4、1.5 和 1.6 上都试过了,效果很好

    【讨论】:

    • 我前几天下载了Gson 1.6版。也许这里还有其他事情发生。
    • 感谢您的回答。它帮助我弄清楚到底发生了什么。 +1
    • 你想在这里分享它以防其他人偶然发现这个吗?
    猜你喜欢
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 2013-11-26
    相关资源
    最近更新 更多