【问题标题】:serialize and deserialize self reference object in c#在 C# 中序列化和反序列化自引用对象
【发布时间】:2015-09-16 06:37:56
【问题描述】:

我有这样的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,但我无法反序列化并收到异常

'无法保留对数组的引用'

。 任何想法序列化和反序列化它?

【问题讨论】:

    标签: c# json serialization deserialization


    【解决方案1】:

    所以看起来这样做是为了防止 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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 2014-12-24
      • 2013-04-11
      • 1970-01-01
      相关资源
      最近更新 更多