我有一个像这样的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/