static void Main() { var circularTest = new CircularTest(); circularTest.Children = new[] { circularTest }; var settings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects }; var json = JsonConvert.SerializeObject(circularTest, Formatting.Indented, settings); Console.WriteLine(json); }
static void Main() { var circularTest = new CircularTest(); circularTest.Children = new[] { circularTest }; var serializer = new DataContractSerializer( circularTest.GetType(), null, 100, false, true, // <!-- that's the important bit and indicates circular references null ); serializer.WriteObject(Console.OpenStandardOutput(), circularTest); }
static void Main() { var circularTest = new CircularTest(); circularTest.Children = new[] { circularTest }; var formatter = new BinaryFormatter(); using (var stream = File.Create("serialized.bin")) { formatter.Serialize(stream, circularTest); } using (var stream = File.OpenRead("serialized.bin")) { circularTest = (CircularTest)formatter.Deserialize(stream); } }