java的gson类,Java类型作为GSON的参数

In GSON to get a list of objects you do

Gson gson = new Gson();

Type token = new TypeToken>(){}.getType();

return gson.fromJson(json, token);

It works great, but I want to go further and have MyType parametrized so I can have a common function to parse list of objects with this code

// the common function

public List fromJSonList(String json, Class type) {

Gson gson = new Gson();

Type collectionType = new TypeToken>(){}.getType();

return gson.fromJson(json, collectionType);

}

// the call

List myTypes = parser.fromJSonList(jsonString, MyType.class);

Sadly returns an array of StringMaps, not the type. T is being interpreted as another generic type, not my type. Any workaround ?

解决方案

Generics work at compile-time. The reason super-type tokens work, is because (anonymous) inner classes can access the type arguments to their generic superclasses (superinterfaces), which in turn are stored directly in the bytecode metadata.

Once your .java source file is compiled, the type parameter is obviously thrown away. Since it is not known at compile time, it cannot be stored in bytecode, so it's erased and Gson can't read it.

UPDATE

After newacct's answer, I tried to implement what he suggested in his option 2, ie implementing a ParameterizedType. The code looks like this (here is a basic test):

class ListOfSomething implements ParameterizedType {

private Class> wrapped;

public ListOfSomething(Class wrapped) {

this.wrapped = wrapped;

}

public Type[] getActualTypeArguments() {

return new Type[] {wrapped};

}

public Type getRawType() {

return List.class;

}

public Type getOwnerType() {

return null;

}

}

the purpose of this code, is to be used inside getFromJsonList():

public List fromJsonList(String json, Class klass) {

Gson gson = new Gson();

return gson.fromJson(json, new ListOfSomething(klass));

}

Even if the technique works and is indeed very clever (I didn't know it and I would have never thinked of it), this is the final accomplishment:

List list = new Factory()

.getFromJsonList(text, Integer.class)

instead of

List list = new Gson().fromJson(text,

new TypeToken>(){}.getType());

To me, all this wrapping in useless, even if I agree that TypeTokens make the code look nasty :P

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值