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

时间:2022-10-29 19:45:17

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.
Unfortunately, I can't touch the objects, since they are in a referenced DLL from another project - otherwise I'd change them.

我尝试将Proposal序列化为Json,它告诉我有一个循环引用,这是正确的。不幸的是,我无法触摸对象,因为它们位于另一个项目的引用DLL中 - 否则我会更改它们。

Is there a way to serialize as Json and ignore the circular properties?

有没有办法序列化为Json并忽略圆形属性?

1 个解决方案

#1


5  

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应用程序,也可以全局定义此变量...

#1


5  

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应用程序,也可以全局定义此变量...