简体   繁体   中英

serialization object reference with Gson

I'm working on a map builder application. It have bus, train, stations, and lines between stations. All those data are stored in a class called 'Map'.

I need to store my Map instance into a JSON file. I choose to use Gson. Here's my Map, Line and Station classes:

 public class Map
 {
    private LinkedList<Station> stations;
    private LinkedList<Line> lines;

    // methods ...
 }

public class Line
{

    private String name;
    private LinkedList<Station> stations;

    // methods
}

public class Station
{

    private int number;
    private String name;
    private double latitude;
    private double longitude;
    private String cityName;

        // methods
}

My problem is than all my object are store as independent object (without any reference). As you can see map contains stations and lines. And lines contains stations. When I load the JSON, and change a station in the map class, the same station doesn't change because it's not linked by reference.

Take a look at this one.

http://code.google.com/p/json-io/

See if it preserves your 'graph of objects' semantics.

Also look at:

http://benjamin.smedbergs.us/blog/2008-08-21/json-serialization-of-interconnected-object-graphs/

http://www.jspon.org/#JSPON%20Core%20Spec

I am not really sure JSON in its original form supports what you want (and you want to
serialize and then properly deserialize a whole graph of objects, not just a tree of objects).
I guess JSON does not support that but I am not 100% sure (I haven't needed that myself).
In a tree each object has just 1 parent, so there you don't have issues.
In a graph you may have objects A and B both pointing to some object C.
So how do you serialize C now? Do you do it in A (ie while serializing A) or in B, or
outside of both A and B, and then have A and B point to that single serialized C somehow?
Or do you just serialize C twice (once in A and once in B)? Btw, isn't it the
same with XML? I guess both XML and JSON are not designed for this.

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