首页 > 解决方案 > 在 C# 中使用 JSON.NET 序列化对象列表

问题描述

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

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 }

现在我想List<Product>用 JSON.NET 将它序列化为 JSON。我试过了:

var json = JsonConvert.SerializeObject(products);

但我收到以下错误:

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

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

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

任何想法我做错了什么?我可以提供更多/更好的信息吗?提前致谢:)

标签: c#nhibernatejson.netasp.net-core-2.0

解决方案


您应该使用JsonConvert默认设置而不是SerializerSettings

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

推荐阅读