在c#中序列化和反序列化自引用对象

时间:2015-06-29 17:20:22

标签: c# json serialization deserialization

我有一个像这样的A级

class A
    {
        public string Type { get; set; }
        public object[] Content { get; set; }
        public string[] jsonContent { get; set; }

        public A()
        {

        }

        public A(string type)
        {
            this.Type = type;
        }

        public A(string type, object[] content)
        {
            this.Type = type;
            this.Content = content;
        }

        public string ToJson()
        {
        int len = Content.Length;
        string[] jsonContentTmp = new string[len];
        for (int i = 0; i < Content.Length; ++i)
        {
            jsonContentTmp[i] = JsonConvert.SerializeObject(Content[i]);
        }
        jsonContent = jsonContentTmp;
        var json = JsonConvert.SerializeObject(this);
        return json;
        }

        public static A ToA(string str)
        {
        Request a = JsonConvert.DeserializeObject<A>(str);
        return a;
        }
    }

考虑一下:

A sub1 = new A();
A sub2 = new A();
object[] obj = {sub1, sub2};
A test = new A("type", obj);

当我想序列化test时,我收到异常

  

自我引用

我尝试PreserveReferencesHandling但我无法反序列化并收到异常

  

&#39;无法保留对阵列的引用&#39;

。 有什么想要序列化和反序列化吗?

1 个答案:

答案 0 :(得分:0)

所以看来这是为了防止Stackoverflow异常。没有双关语。您必须打开PreserveReferences,才能启用自引用:

Serialising Circular references

在Global.asax的AppStart中尝试以下操作:

var jsonSerializerSettings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonNetFormatter(jsonSerializerSettings));