c# - 在 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;
任何想法我做错了什么?我可以提供更多/更好的信息吗?提前致谢:)
解决方案
您应该使用JsonConvert
默认设置而不是SerializerSettings
:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
推荐阅读
- python - 显示对特定博客文章唯一的评论
- javascript - 我如何路由参数错误?
- microsoft-graph-api - 获取 /me/events/{id} 返回不正确的日历对象
- javascript - 如何使用来自“react-file-picker”的 FilePicker 在 React 中显示用户上传的 PDF?
- random - 从内核分布生成随机数 simulink
- android - Firebase 机器学习套件、谷歌云视觉 API 或 openCV
- python - 在用户输入的函数中是否有多个 while True 循环的替代方法?
- angular - 错误:未捕获(承诺中):无法匹配任何路由。URL 段:部署 Angular Universal SSR 应用程序时的“simplewebtool/us-central1/ssr”
- r - 在没有安装 rgdal 的情况下在 R 中解压缩和读取形状文件
- postgresql - 无法将 postgresql db 连接到我的 netcore Web 项目(DigitalOcean Cloud)