I’ve a small app in Android which have to comunicate with a server through a socket. The question is: can I use Gson to serialize the references of the object?
I make an example:
if I have a B class like this:
public class B{
int n;
public B(int n){
this.n=n;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public B() {
super();
}
}
and an A class like this
public class A{
B b1;
B b2;
B b3;
public B getB1() {
return b1;
}
public void setB1(B b1) {
this.b1 = b1;
}
public B getB2() {
return b2;
}
public void setB2(B b2) {
this.b2 = b2;
}
public B getB3() {
return b3;
}
public void setB3(B b3) {
this.b3 = b3;
}
public A(B b1, B b2, B b3) {
super();
this.b1 = b1;
this.b2 = b2;
this.b3 = b3;
}
public A() {
super();
}
}
and than I call
B b1 = new B(1); B b2 = new B(2)
A a = new A(b1,b1,b2);
if I serialize (with (new Gson()).toJson(a,A.class) the a object I obtain
{"b1":{"n":1},"b2":{"n":1},"b3":{"n":2}}
but I’d prefer have something link this
{istance1:{b1: {"b1":istance2,"b2":istance2,"b3":istance2},istance2: {"n":1},istance3:{"n":2}}
Can you help me? I read a lot of pages but I didn’t find anything!
Take a look at GraphAdapterBuilder, which can do this. You’ll need to copy that file into your application because it isn’t included in Gson.
https://code.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java