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?
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.
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 become serializable? Explanation: A Java object is serializable if class or any its superclass implements java. io. Serializable or its subinterface java.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With