gpt4 book ai didi

Java Gson 在 HashMap 中序列化和反序列化对象(key,Object)

转载 作者:行者123 更新时间:2023-12-02 03:40:39 25 4
gpt4 key购买 nike

我有以下代码作为我想要实现的目标的示例:

public static void main(String args[]) {

Map<String, Object> map = new HashMap<String, Object>();
map.put("1", new A());
map.put("2", new B());
String json = new Gson().toJson(map);
Type type = new TypeToken<Map<String, Object>>(){}.getType();
map = new Gson().fromJson(json, type);
A a = (A) map.get("1");
B b = (B) map.get("2");

}

static class A {

int inum = 1;
double dnum = 1.0;
String str = "1";

}

static class B {

int inum = 2;
double dnum = 2.0;
String str = "2";

}

以下代码会导致此异常:

Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to ParseJson$A
at ParseJson.main(ParseJson.java:19)

所以问题是:如何在 Gson 序列化和反序列化的通用 HashMap 中获取正确的实例?

最佳答案

Object 被反序列化为 com.google.gson.internal.LinkedTreeMap,因此告诉 Gson 您想要 A 类。

public static void main(String args[]) {
Map<String, Object> map = new HashMap<>();
map.put("1", new A());
String json = new Gson().toJson(map);
Type type = new TypeToken<Map<String, A>>() {
}.getType();
map = new Gson().fromJson(json, type);
A a = (A) map.get("1");
System.out.println(a.str);
}

static class A {
private int num1 = 1;
private double num2 = 2.0;
private String str = "String";
}

希望有帮助。

更新

基类(在本例中为X)可能是一个解决方案:

public static void main(String args[]) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("1", new A());
map.put("2", new B());
String json = new Gson().toJson(map);
Type type = new TypeToken<Map<String, X>>(){}.getType();
map = new Gson().fromJson(json, type);
X a = (X) map.get("1");
X b = (X) map.get("2");
System.out.println(a.str);
System.out.println(b.str);
}

static class X {
int inum;
double dnum;
String str;

X() {
}
}

static class A extends X {
A() {
inum = 1;
dnum = 1.0;
str = "1";
}
}

static class B extends X {
B() {
inum = 2;
dnum = 2.0;
str = "2";
}
}

关于Java Gson 在 HashMap 中序列化和反序列化对象(key,Object),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36869828/

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