mim*_*imo 6 c# serialization json json.net
我的模型类如下所示:
public class ModelType
{
public string Name { get; set; }
public ModelType SuperType { get; set }
public IEnumerable<ModelType> SubTypes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我试图序列化对象,但得到StackOverflowException.我试着打电话
JsonConvert.SerializeObject(model, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Run Code Online (Sandbox Code Playgroud)
以及
JsonConvert.SerializeObject(model, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
Run Code Online (Sandbox Code Playgroud)
这两个电话都导致了StackOverflowException.知道如何序列化ModelType实例吗?
编辑:
实例示例,无法序列化:
{
Name: "Child",
SuperType: {
Name: "Parent",
SuperType: null,
SubTypes: [{
Name: "Child",
SuperType: {
Name: "Parent",
SuperType: null,
SubTypes: [{Name: "Child", ...}]
},
SubTypes: []
}]
},
SubTypes: []
}
Run Code Online (Sandbox Code Playgroud)
编辑2:
通过进一步调查问题(根据所有SO Q&A,设置ReferenceLoopHandling.Ignore或PreserveReferencesHandling.Objects应该工作)我发现了这一点
我认为,在对象创建过程中出现问题(在我的代码之外),这创建了无限的对象链.我不确定这是否甚至可以处理JsonSerializerSettings.
Newtonsoft.Json 可以有以下配置
JsonSerializerSettings sets = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
var ser = JsonSerializer.Create(sets);
Run Code Online (Sandbox Code Playgroud)
你可能想这样做。
| 归档时间: |
|
| 查看次数: |
10159 次 |
| 最近记录: |