Circular reference error in Object Serialization in Asp.Net using C#

Category object is a typical object that requires parent/children relationship. What's more, it is a common practice that the child object will require a parent object reference.

When we use object serialization, it is very important that we set the parent object as [XmlIgnore]. Otherwise, the serialization will raise an exception as following:

Circular reference was detected while serializing an object Categories.

The following is the code sample.

///
/// Summary description for Categories
///

public class Categories
{
[XmlIgnore]
public Categories m_parentCategory;

public Guid m_CategoryID;
public string m_CategoryName = "";
public short m_iLevel = 0;
public static Categories rootCategory = null;

public List m_oSubCategories = new List();

public void Save(string fileName)
{
FileStream fileStreamCreate = new FileStream(fileName, FileMode.Create);
XmlSerializer serializerCategory = new XmlSerializer(typeof(Categories));
serializerCategory.Serialize(fileStreamCreate, this);
fileStreamCreate.Close();
return;
}

public Categories LoadCategories(string fileName)
{
try
{
FileStream fileStreamRead = new FileStream(fileName, FileMode.Open);
XmlSerializer deSerializer = new XmlSerializer(typeof(Categories));
Categories oNewCat = (Categories)deSerializer.Deserialize(fileStreamRead);
fileStreamRead.Close();
return oNewCat;
}
catch
{
}
return null;
}
}

Comments

Popular posts from this blog

Javascript Hosted on Google Drive Not Working Reliably

Newsmag Theme and External Featured Image

Responsive Web Design