Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is It possible to perform serialization with circular references?

So, my entity class (written in C#) follows a parent child model where every child object must have a Parent property in which it keeps reference of its Parent.

This Parent property causes issues in serialization of the Object due to circular references.

I can't remove the reference to parent, neither I can mark it XmlIgnore (since I need to read it back when I deserialize the XML)

Any ideas on this?

like image 635
Arpit Khandelwal Avatar asked Feb 15 '11 13:02

Arpit Khandelwal


People also ask

Are circular references OK?

Circular Reference means that your formula is trying to calculate the origin cell. Typically, this is considered an error. However, there are times where this error can actually be useful and you might to want to create a circular reference on purpose.

What is serialization in .NET with example?

Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is deserialization, which converts a stream into an object. Together, these processes allow data to be stored and transferred. .

What is the benefit of serialization in C#?

Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions such as: Sending the object to a remote application by using a web service.


2 Answers

XML serialization doesn't support circular references, you need to exclude the parent property from the serialization using the XmlIgnore attribute. See this blog post for a way to maintain the relationship when you deserialize.

Alternatively, you could use DataContractSerializer instead of XmlSerializer. It supports circular references, but doesn't provide much control over the XML schema...

like image 130
Thomas Levesque Avatar answered Oct 10 '22 15:10

Thomas Levesque


You can either create your own XMLSerializer or use the DataContractSerializer and the [DataContract(IsReference= true)] attribute to tell the serializer to remember the references.

like image 36
Yuriy Faktorovich Avatar answered Oct 10 '22 14:10

Yuriy Faktorovich