java泛型如何解决反序列化,如何将GSON反序列化为相应的泛型Java类型?

I want to deserialize a JSON object (using GSON, because I already use it for searializing objects) to a general Map of type Map. It should create Objects of types that do correspond to the according JSON types, i.e. this JSON Object

{

"docID" : "a12345",

"relation" : ["1", "2", "3"],

"title" : { "de" : "German Title",

"en" : "English Title"}

}

should be deserialized in a Map with entries of the following types:

(String, String), (String, List), (String, Map).

I tried to use the following code:

class Dictionary_ extends HashMap {

// nothing to do

};

private static final GsonBuilder GSON_BUILDER = new GsonBuilder();

public Map deserializeJsonString(String jsonString) {

Dictionary_ d = new Dictionary();

return GSON_BUILDER.create().fromJson(jsonString, d.getClass());

}

But then the resulting types of created Objects are as follows:

(String, Object), (String, Object), (String, Object)

and I am not able to cast these objects into the corresponding "real" types, because I get class cast exceptions.

I am not able to use POJOs, since the data I am receiving does not have predefined structure in terms of class members.

So, how am I able to deserialize such generic data in according generic Java types?

Update:

I just tried to implement it using JSON Simple, and it works out of the box very easily by the following code:

Object ret = JSONValue.parse(jsonString);

return (List>) ret;

Why does it not work that easy with GSON???

解决方案

The structure that JSON.simple deserialized into was a Map, where each entry key is a String, and each entry value is either a simple data type or another Map.

Deserializing to such a structure with Gson is unfortunately not as simple as I think it should be, taking a few dozen lines of code. I posted an example of doing so at http://programmerbruce.blogspot.com/2011/06/gson-v-jackson.html. (Search for the phrase "Gson Code to turn any JSON object into a Map" to jump straight to the relevant example.)

That blog post also includes an example of using Jackson to accomplish the same task with just one line of code. (I highly recommend abandoning Gson in favor of Jackson, whenever possible.)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值