简体   繁体   English

序列化循环引用对象的最佳方法是什么?

[英]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. 最好的是json,有一些标准指针。 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: DataContractSerializer也可以处理循环引用,你只需要使用一个特殊的构造函数并指出它并且它将吐出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: 最新版本的Json.NET也支持循环引用和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. 我想这就是你所问的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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