简体   繁体   English

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

[英]serialize and deserialize self reference object in c#

I have a class A like this 我有这样的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;
        }
    }

Consider bellow: 考虑一下:

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

When I want to serialize test , I receive exception 当我想序列化test ,我收到异常

self reference 自我参考

I tried PreserveReferencesHandling but i couldn't deserialize and receive exception 我尝试过PreserveReferencesHandling但我无法反序列化并接收异常

'cannot preserve reference toarray' '无法保留对阵列的引用'

. Any idea to serialize and deserialize it? 有什么想法序列化和反序列化吗?

So it seems this is done on purpose to prevent Stackoverflow exceptions. 所以看起来这是为了防止Stackoverflow异常。 No pun intended. 没有双关语。 You have to turn PreserveReferences on, to enable self referencing: 您必须打开PreserveReferences,才能启用自引用:

Serialising Circular references 序列化循环引用

In your AppStart in Global.asax try the following: 在Global.asax的AppStart中,尝试以下操作:

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

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

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

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