在C#中使用JSON.NET序列化对象列表 [英] Serialize list of objects with JSON.NET in C#

查看:82
本文介绍了在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
};

这篇关于在C#中使用JSON.NET序列化对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆