gson和参考 [英] gson and references

查看:79
本文介绍了gson和参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android中有一个小型应用程序,必须通过套接字与服务器通信.问题是:我可以使用Gson序列化对象的引用吗?

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?

我举一个例子: 如果我有这样的B类:

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();
    }
}

和这样的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),则是我获得的对象

if I serialize (with (new Gson()).toJson(a,A.class) the a object I obtain

{"b1":{"n":1},"b2":{"n":1},"b3":{"n":2}}

但是我希望有一些链接

{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!

推荐答案

看看GraphAdapterBuilder可以做到这一点.您需要将该文件复制到您的应用程序中,因为它不包含在Gson中.

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.

Roshambo rock = new Roshambo("ROCK");
Roshambo scissors = new Roshambo("SCISSORS");
Roshambo paper = new Roshambo("PAPER");
rock.beats = scissors;
scissors.beats = paper;
paper.beats = rock;

GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
    .addType(Roshambo.class)
    .registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();

assertEquals("{'0x1':{'name':'ROCK','beats':'0x2'}," +
    "'0x2':{'name':'SCISSORS','beats':'0x3'}," +
    "'0x3':{'name':'PAPER','beats':'0x1'}}",
    gson.toJson(rock).replace('\"', '\''));

https://code.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java

这篇关于gson和参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆