gpt4 book ai didi

java - Gson反序列化时失败 "understand"泛型类型

转载 作者:行者123 更新时间:2023-11-30 04:26:00 29 4
gpt4 key购买 nike

我创建了这个内存类:

public class Memory {
private final Hashtable<String, String> data;
private final Gson gson;

public Memory() {
this.data = new Hashtable<String, String>();
this.gson = new Gson();
}

public <T> void set(String key, List<T> value) {
this.data.put(key, this.gson.toJson(value));
}

public <T> List<T> get(String key, Class<T> cls) {
Type type = new TypeToken<List<T>>() {}.getType();
return this.gson.fromJson(this.data.get(key), type);
}
}


我可以在 json 中存储泛型类型列表,然后反序列化它们。
但是当我尝试使用它时,例如像这样:

public class User {
private int id;
private String username;

public User() { }

public User(int id, String username) {
this.id = id;
this.username = username;
}
}

Memory memory = new Memory();
List<User> users = new ArrayList<User>();
// add users
memory.set("users", users);

// now get the users back
List<User> copy = memory.get("users", User.class);

Gson 返回 StringMap 的 ArrayList 而不是 Users。
这显然与我正在使用的泛型有关,但是有没有办法绕过它?

谢谢。

最佳答案

这里真正的失败在于 Java 泛型允许的明显不一致,其中 List<User>最终被 com.google.gson.internal.StringMap 的实例填充!但这完全是另一个话题了。

眼前的问题是您没有正确使用类型标记类。该 token 的要点在于,您必须使用具体类型扩展该类 - 然而,您正在使用方法级泛型参数实例化该类,该参数在编译时进行验证,然后删除(随后在运行时不可用)。但类型标记的全部要点是保留通用信息,因此模型失败了。

说实话,这是 token 实现的失败 - 如果您将构造函数代码与 TypeReference implementation of Jackson 等进行比较。 ,您会看到 Jackson 实际上验证了具体参数是否可用。

31    protected TypeReference()
32 {
33 Type superClass = getClass().getGenericSuperclass();
34 if (superClass instanceof Class<?>) { // sanity check, should never happen
35 throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information");
36 }
45 }

最简单的解决方案是简单地让调用者负责构造类型( token ),并将其与您希望存储和/或检索的数据一起传递。

public <T> List<T> get(String key, Type type) {
return this.gson.fromJson(this.data.get(key), type);
}

public <T> void set(String key, List<T> value, Type type) {
this.data.put(key, this.gson.toJson(value, type));
}

关于java - Gson反序列化时失败 "understand"泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15865234/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com