Object graph for type contains cycles and cannot be serialized
This issue occurs when parent and child classes has cyclic reference and when you tries to serialize it to json or xml. See the following code which gives the error.
- [DataContract]
- public class Family
- {
- [DataMember]
- public IList<Parent> Parents;
- [DataMember]
- public IList<Child> Children;
- }
- [DataContract]
- public class Parent
- {
- [DataMember]
- public string Name { get; set; }
- [DataMember]
- public IList<Child> Children { get; set; }
- }
- [DataContract]
- public class Child
- {
- [DataMember]
- public string Name { get; set; }
- [DataMember]
- public Parent Father { get; set; }
- [DataMember]
- public Parent Mother { get; set; }
- }
This is the sample object
- var dad = new Parent { Name = "John" };
- var mum = new Parent { Name = "Mary" };
- var kid1 = new Child { Name = "Ann", Mother = mum, Father = dad };
- var kid2 = new Child { Name = "Barry", Mother = mum, Father = dad };
- var kid3 = new Child { Name = "Charlie", Mother = mum, Father = dad };
- var listOfKids = new List<Child> { kid1, kid2, kid3 };
- dad.Children = listOfKids;
- mum.Children = listOfKids;
- var family = new Family { Parents = new List<Parent> { mum, dad }, Children = listOfKids };
When I tried to serialize this object using data contract serializer I go the cyclic reference error. Following is the code I used to serialize this object in to json.
- DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Family));
- MemoryStream ms = new MemoryStream();
- ser.WriteObject(ms, family);
- string jsonString = Encoding.UTF8.GetString(ms.ToArray());
- ms.Close();
- return jsonString;
Json.Net gives the solution for this. I my case I don’t want cyclic references to be serialized. So following is the solution I came up.
1. Reference json .net to your project. Use the following nuget
PM> Install-Package NewtonSoft.Json
2. Then add follwong using statement to your class.
- using Newtonsoft.Json;
3. Then use the following code. It will ignore the cyclic references and serialize the object without any issue.
{
MissingMemberHandling = MissingMemberHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
using (var jtw = new JsonTextWriter(sw))
jsonSerializer.Serialize(jtw, family);
var result = sb.ToString();
for more details on this error please go here
Hope this helps
Happy Coding !!!!!!
Comments
Post a Comment