在c#中序列化和反序列化自引用对象
本文关键字:反序列化 自引用 对象 序列化 | 更新日期: 2023-09-27 18:00:18
我有一个类似的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
,但无法反序列化并接收异常
"无法保留对数组的引用"
有没有序列化和反序列化的想法?
所以这样做似乎是为了防止堆栈溢出异常。无意双关。您必须打开"保留引用",才能启用自引用:
系列化通告参考
在Global.asax中的AppStart中,尝试以下操作:
var jsonSerializerSettings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonNetFormatter(jsonSerializerSettings));