What is the best way to serialize circular referenced objects?

It is better that the text be text. The best would be json, with some standard pointers. Binary would be good too. Remember, in the old days soap had a standard for this. What are you offering?

+6
source share
1 answer

No problem with binary :

[Serializable] public class CircularTest { public CircularTest[] Children { get; set; } } class Program { 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); } } } 

A DataContractSerializer can also handle circular references, you just need to use a special constructor and specify this, and it will spit XML:

 public class CircularTest { public CircularTest[] Children { get; set; } } class Program { static void Main() { var circularTest = new CircularTest(); circularTest.Children = new[] { circularTest }; var serializer = new DataContractSerializer( circularTest.GetType(), null, 100, false, true, // <!-- that the important bit and indicates circular references null ); serializer.WriteObject(Console.OpenStandardOutput(), circularTest); } } 

And the latest version of Json.NET supports circular links, as well as with JSON:

 public class CircularTest { public CircularTest[] Children { get; set; } } class Program { 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); } } 

gives:

 { "$id": "1", "Children": [ { "$ref": "1" } ] } 

which I think of is what you asked for.

+9
source

Source: https://habr.com/ru/post/898007/


All Articles