Serialize list of objects with JSON.NET in C#

不羁的心 提交于 2019-12-25 01:45:47

问题


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);

A product looks like this:

//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 }

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

var json = JsonConvert.SerializeObject(products);

But I get the following error:

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

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:)


回答1:


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

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


来源:https://stackoverflow.com/questions/52034881/serialize-list-of-objects-with-json-net-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!