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

标签 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时,我收到异常

self reference

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

'cannot preserve reference toarray'

. 有序列化和反序列化它的想法吗?

最佳答案

所以这似乎是故意这样做的,以防止 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));

关于c# - 在 C# 中序列化和反序列化自引用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31121778/

相关文章:

c# - ContentView 中的按钮导致 MonoTouch 运行时崩溃。 Monotouch 4.0 中的错误?

Python根据键值对更新字典

java - 将字符串从 Java 文件传递​​到 jQuery

java动态属性表

java - 我们可以使用可序列化将一组对象从一个 Activity 传递到另一个 Activity 吗

c# - ilasm 的问题

c# - 可以修改 Linq To SQL 生成的 C# 吗?

c# - 第一次发送消息到错误队列

java - 使用Gson解析对象内部的Json对象并获取长度

c# - Entity Framework 和 DataContractSerializer