开发者

What is the best way to serialize circular referenced objects?

开发者 https://www.devze.com 2023-04-07 02:19 出处:网络
Better that should be text format. The best would be json, with some standart to pointers. Binary would be also good. Remember in o开发者_如何转开发ld times, soap has standart for this. What you sugge

Better that should be text format. The best would be json, with some standart to pointers. Binary would be also good. Remember in o开发者_如何转开发ld 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消