简体   繁体   中英

serialize and deserialize self reference object in c#

I have a class A like this

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

self reference

I tried PreserveReferencesHandling but i couldn't deserialize and receive exception

'cannot preserve reference toarray'

. Any idea to serialize and deserialize it?

So it seems this is done on purpose to prevent Stackoverflow exceptions. No pun intended. You have to turn PreserveReferences on, to enable self referencing:

Serialising Circular references

In your AppStart in Global.asax try the following:

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

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

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