json cycle stackoverflowexception error

Dec 20, 2010 at 12:42 PM

Hi,

I was trying to serialize the following set of classes. Class X is referenced by class Y and class Y is referenced by class X. The code is as below. I have set the ReferenceLoopHandling to Serialize but i am getting a stackoverflowexception. Any ideas on how we can rectify this.

Thanks

Yang

 

  public class X
    {
 
        public string Name { get; set; }
        public Y y { get; set; }
    }
 
   public class Y
    {
 
        public int ID { get; set; }
        public X x { get ; set  ;}
    }

 

using (MemoryStream mem = new MemoryStream())
            {
                X x1 = new X();
                x1.Name = "yang";
                Y y1 = new Y();
                y1.ID = 20;
                y1.x = x1;
                x1.y = y1;
               
                JsonSerializer serializer = new JsonSerializer();
                StreamWriter strWriter = new StreamWriter(mem);
                JsonWriter writer = new JsonTextWriter(strWriter);
                serializer.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
                serializer.Serialize(writer, x1);
                writer.Flush();
                
                mem.Position = 0;
                StreamReader reader = new StreamReader(mem);
                Console.WriteLine(reader.ReadToEnd());
            }