What is an object graph and how do I serialize one

pkolodziej picture pkolodziej · May 18, 2009 · Viewed 20.9k times · Source

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?

Answer

Marc Gravell picture Marc Gravell · May 18, 2009

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:

<Node>
  <Name>A</Name>
  <!-- no Parent as A is the top node, so null -->
  <Children>
     <Node>
        <Name>B</Name>
        <Parent>
           <Node>
              <Name>A</Name>
              *** 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:

[XmlIgnore]
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.