Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gson and references

Tags:

java

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?

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!

like image 672
Alberto Avatar asked Dec 03 '25 17:12

Alberto


1 Answers

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

like image 162
Jesse Wilson Avatar answered Dec 06 '25 08:12

Jesse Wilson