简体   繁体   中英

What is the best way to serialize circular referenced objects?

Better that should be text format. The best would be json, with some standart to pointers. Binary would be also good. Remember in old times, soap has standart for this. What you suggest?

No problem with binary whatsoever:

[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 cope with circular references, you just need to use a special constructor and indicate 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's the important bit and indicates circular references
            null
        );
        serializer.WriteObject(Console.OpenStandardOutput(), circularTest);
    }
}

And the latest version of Json.NET supports circular references as well 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);
    }
}

produces:

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

which I guess is what you was asking about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM