Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 962
pkolodziej Avatar asked May 18 '09 10:05

pkolodziej


People also ask

What is an object graph in C#?

The object graph type is one of six fundamental types defined by GraphQL. We can think of a graph query like a tree and if scalar values, such as string and int , are the leafs then objects are the branches. In GraphQL ASP.NET a C# class or struct is used to identify an OBJECT type in a schema.

What is used for object serialization?

For serializing the object we have used ObjectOutputStream. We have used the method writeObject to write the object in the file. For Deserializing we have used ObjectInputStream which reads from the object from the file. It uses readObject to read the object data from the file.

How an object can becomes serializable?

How an object can become serializable? Explanation: A Java object is serializable if class or any its superclass implements java. io. Serializable or its subinterface java.


1 Answers

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.

like image 169
Marc Gravell Avatar answered Sep 19 '22 11:09

Marc Gravell