在C#中使用JSON.NET序列化对象列表

在C#中使用JSON.NET序列化对象列表

问题描述:

我有一个看起来像这样的列表:

I have a List that looks like:

List<Product> products = new List<Product>();
Product p1 = new Product(1, "Apple", new Description("Red Apple"))
Product p2 = new Product(2, "Banana", new Description("Yellow Banana"))
products.Add(p1);
products.Add(p2);

产品看起来像这样:

//Product model
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Description descriptions { get; set; }

//Description model
public string description { get; set }

现在,我想使用JSON.NET将List<Product>序列化为JSON.我尝试过:

Now I want to serialize this List<Product> to JSON with JSON.NET. I've tried:

var json = JsonConvert.SerializeObject(products);

但是出现以下错误:

Newtonsoft.Json.JsonSerializationException: 'Self referencing loop detected for property 'Module' with type 'System.Reflection.RuntimeModule'.

我的Startup.cs文件中还有以下行应避免循环:

I also have the following line in my Startup.cs file that should avoid loops:

xy.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

有什么主意我做错了吗?我可以提供更多/更好的信息吗? 在此先感谢:)

Any ideas what I'm doing wrong? Can I provide more/better informations? Thanks in advance:)

您应该使用JsonConvert的默认设置,而不要使用SerializerSettings:

You should use JsonConvert's default Setting rather than SerializerSettings:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};