简体   繁体   English

如何将带有循环引用的对象结构序列化为Json?

[英]How to serialize as Json an object structure with circular references?

I have an object structure like this: 我有一个像这样的对象结构:

public class Proposal {
    public List<ProposalLine> Lines { get; set; }
    public string Title { get; set; }
}

public class ProposalLine {
    public Proposal Proposal { get; set; }  // <- Reference to parent object
}

I try to serialize Proposal as Json, it tells me that there is a circular reference, which is correct. 我尝试将Proposal序列化为Json,它告诉我有一个循环引用,这是正确的。
Unfortunately, I can't touch the objects, since they are in a referenced DLL from another project - otherwise I'd change them. 不幸的是,我无法触摸对象,因为它们位于另一个项目的引用DLL中 - 否则我会更改它们。

Is there a way to serialize as Json and ignore the circular properties? 有没有办法序列化为Json并忽略圆形属性?

Use the Newtonsoft.Json (which is the default .net json serializer) and set 使用Newtonsoft.Json(默认的.net json序列化程序)并设置

JsonSerializerSettings settings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
var serializer = JsonSerializer.Create(settings);

You can also globally define this variable if you are developing MVC applications... 如果您正在开发MVC应用程序,也可以全局定义此变量...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM