gson 获取hasmap_JSON使用Java中的GSON对使用HashMap成员的自定义类进行解码

I have the following class:

class IndexItem {

private String word;

private HashMap docs;

private Integer total;

public IndexItem(String word) {

this.total = 0;

this.docs = new HashMap();

this.word = word;

}

public IndexItem() {

this.total = 0;

this.docs = new HashMap();

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?

解决方案

Sorry to answer my own question, but...

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值