I have several classes that contain a recursive dependency on each other and I serialize them to JSON format with Gson GraphAdapterBuilder, and it works perfectly. Now I want to deserialize them into the same structure but can't find out how.
I've made an example:
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);
Output is giving me what I want:
{"0x1":{"vector":["0x2","0x3","0x4"]},"0x2":{"field":1,"parent":"0x1"},"0x3":{"field":2,"parent":"0x1"},"0x4":{"field":3,"parent":"0x1"}}
Is there a way to deserialize that json string back into object of ClassB?
Okay, I found solution. It was very simple. Just had to use the function fromJson instead of toJson with the same GraphAdapterBuilder structure.
...
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
.addType(ClassA.class)
.addType(ClassB.class)
.registerOn(gsonBuilder);
gson = gsonBuilder.create();
СlassB B = gson.fromJson(json,ClassB.class);
System.out.println("B " + B.vector);
for(ClassA classA:B.vector){
System.out.println(classA.field + " " + classA.parent);
}
Output is:
B [ClassA@10178f2b, ClassA@7ab8584d, ClassA@5cad662c]
1 ClassB@7c0f023c
2 ClassB@7c0f023c
3 ClassB@7c0f023c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With