【发布时间】:2011-05-26 12:50:44
【问题描述】:
将 json 字符串反序列化为带有类型参数的类型似乎是不可能的。
我想写一个这样的函数:
public <T> Value<T> getValue (json, Class<T> clazz) {
// THE PROBLEM: T becomes Object so the resulting
// Value will hold an Object as value
Type type = new TypeToken<Value<T>>() {}.getType();
return gson.fromJson(json, type);
}
一个例子是:
Value<User> value = new Value<User>(
new User("Max", "Hu", new Address("5th Av.","NY")), "infos");
// Works fine
String json gson.toJson(value, new TypeToken<Value<User>>() {}.getType())
// dosen't work
getValue(json, User.class)
对应的类:
class Value<T> {
T value;
String someInfos;
}
class User {
String name;
String lastName;
Address address;
}
class Address {
String street;
String city;
}
我错过了什么吗?
【问题讨论】:
-
您的 JSON 示例不代表数组,但您正试图将其反序列化为
List。因此,您的意图令人困惑。请提供初始 JSON 输入的有效示例。 -
对不起,我花了更少的时间写这个问题。希望现在更清楚了。