none
How can I convert recursive types to JSON RRS feed

  • Question

  • Hi all;

    If this is not the best forum to ask this, please let me know which is (this seems to have the most JSON questions.

    How can I convert an object that has recursive types (not objects, just types)? The following code fails when trying to serialize an object with a parent/child relationship.

    ??? - thanks - dave

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    
    namespace TestJson
    {
    	class Program
    	{
    		static void Main(string[] args)
    		{
    			Adult parent = new Adult {name = "John", age = 42};
    
    			MemoryStream stream1 = new MemoryStream();
    			DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Adult));
    			ser.WriteObject(stream1, parent);
    
    			stream1.Position = 0;
    			StreamReader sr = new StreamReader(stream1);
    			Console.Write("JSON form of Adult with no children: ");
    			Console.WriteLine(sr.ReadToEnd());
    
    
    			Child child = new Child { name = "Jane", age = 4, fingers=10 };
    
    			stream1 = new MemoryStream();
    			ser = new DataContractJsonSerializer(typeof(Child));
    			ser.WriteObject(stream1, child);
    
    			stream1.Position = 0;
    			sr = new StreamReader(stream1);
    			Console.Write("JSON form of Child with no parent: ");
    			Console.WriteLine(sr.ReadToEnd());
    
    
    			// now connect the two
    			parent.children.Add(child);
    
    			stream1 = new MemoryStream();
    			ser = new DataContractJsonSerializer(typeof(Adult));
    			ser.WriteObject(stream1, parent);
    
    			stream1.Position = 0;
    			sr = new StreamReader(stream1);
    			Console.Write("JSON form of Adult with 1 child: ");
    			Console.WriteLine(sr.ReadToEnd());
    		}
    	}
    
    	[DataContract]
    	class Person
    	{
    		[DataMember]
    		internal string name;
    
    		[DataMember]
    		internal int age;
    	}
    
    	[DataContract]
    	class Adult : Person
    	{
    		[DataMember] 
    		internal List<Person> children = new List<Person>();
    	}
    
    	[DataContract]
    	class Child : Person
    	{
    		[DataMember]
    		internal int fingers;
    	}
    }
    


    Who will win The Windward International Collegiate Programming Championships?

    Tuesday, July 23, 2013 4:02 PM

Answers

All replies