【发布时间】:2012-10-20 21:16:14
【问题描述】:
我在 Android 中有一个小应用程序,它必须通过套接字与服务器通信。问题是:我可以使用Gson来序列化对象的引用吗?
我举个例子: 如果我有这样的 B 类:
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();
}
}
还有一个像这样的A类
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();
}
}
比我说的
B b1 = new B(1); B b2 = new B(2)
A a = new A(b1,b1,b2);
如果我序列化(使用(new Gson()).toJson(a,A.class) 我获得的对象
{"b1":{"n":1},"b2":{"n":1},"b3":{"n":2}}
但我更希望有这个链接
{istance1:{b1: {"b1":istance2,"b2":istance2,"b3":istance2},istance2: {"n":1},istance3:{"n":2}}
你能帮帮我吗?我读了很多页,但没有找到任何东西!
【问题讨论】:
-
我也花了很多时间从另一个角度实现这一点,但找不到任何满意的答案。见here。似乎没有对此的本机支持。但是,如果您的服务器可以帮助您识别 json 中的对象类型,那么可能会有一些定制的解决方案。
-
感谢您的回答。我还写了服务器,所以我可以构造序列化器和反序列化器