What is an object graph and how do I serialize one

I've been reading lately about serialization. I've read that when I use XmlSerialization I cannot serialize object graphs. What is an object graph and why I cannot serialize it simply?


An object graph is not a single object, but rather a set of related objects. For a simple example, consider:

public class Node {
    public string Name {...}
    public Node Parent {...}
    public List<Node> Children {...}

where each child knows about the parent (and the parent knows about the child).

The problem is that xml is a tree based on object properties... and it wants to just walk them - i.e. with the simple parent/child:

  • A (knows that B is its child)
    • B (knows that A is its parent)

that would serialize as:

  <!-- no Parent as A is the top node, so null -->
              *** boom ***

You can see that we got back to A, so we're now in an endless loop.

XmlSerializer can serialize trees of data, but not full graphs. You can mark properties to be ignored, for example:

public Node Parent {...}

And now it'll work, but we'll have to fix the Parent afterwards.

By contrast, some other serializers can handle graphs (DataContractSerializer can on-demand). It does this by tracking objects against a unique key - but then the output isn't what you expect from regular xml.

An object graph is a set of objects that reference one another.

Serializing an object graph is tricky. The serializer would have to assign a unique ID to every object and then replace references with unique IDs.

If it was serializing in XML format, and handling object graphs, it would have to add an "OBJECT_ID" (or some other named) attribute to every element. This would be very easy to break: what would happen if you added a property with the same name to the class you are serializing?

The simplest solution is to not support it.

.NET provides binary serialization which deals with this issue as well as the issue of circular references.

A general object graph consists of a set of object holding references to each other. If you have an object tree where there are no backwards links, serialization and deserialization is simple. With a general graph, the (de)serialization process needs to keep track of the identity of each object, and use some form of mark-and-sweep algorithm to ensure that objects aren't (de)serialized twice.

Need Your Help

How to read a text-file resource into Java unit test?

java unit-testing

I have a unit test that needs to work with XML file located in src/test/resources/abc.xml. What is the easiest way just to get the content of the file into String?

Inspect an element to investigate jQuery event bindings

javascript jquery events firebug onclick

Hypothetical: I find a page with a button ('#bigButton'), that when clicked causes a llama ('img#theLlama') to show() using jQuery.