我有几个类彼此之间存在递归依赖关系,并使用Gson GraphAdapterBuilder将它们序列化为JSON格式,效果很好。现在我想将它们反序列化为相同的结构,但无法找到方法。
我制作了一个示例:
class ClassA{
public int field;
public ClassB parent;
public ClassA(int f, ClassB p){
field = f;
parent = p;
}
}
class ClassB{
public Vector<ClassA> vector = new Vector<ClassA>();
}
...
ClassB b = new ClassB();
ClassA a1 = new ClassA(1,b);
ClassA a2 = new ClassA(2,b);
ClassA a3 = new ClassA(3,b);
b.vector.add(a1);
b.vector.add(a2);
b.vector.add(a3);
//Serializing object b
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
.addType(ClassA.class)
.addType(ClassB.class)
.registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
String json = gson.toJson(b);
输出给我想要的结果:
{"0x1":{"vector":["0x2","0x3","0x4"]},"0x2":{"field":1,"parent":"0x1"},"0x3":{"field":2,"parent":"0x1"},"0x4":{"field":3,"parent":"0x1"}}
有没有办法将该 JSON 字符串反序列化为 ClassB 对象?