简体   繁体   中英

gson and references

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.

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

JSON is a standard designed for data interchange. This way, it has some rules that need to be followed in order to "standardize" the communication.

If you want to use GSon to serialize data, you cannot change how it is serialized. That is the pattern

If you really want to produce the serialized data at your way, i think you will also need to produce the Serializer/Deserializer for it!

Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM