在 Json.net 中序列化一对多关系 [英] Serialize one to many relationships in Json.net

查看:18
本文介绍了在 Json.net 中序列化一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用实体​​框架代码进行数据访问,并且我有一个包含员工集合的公司类.Employee 类也有一个 Company 属性.

I am using the Entity Framework code first for data access and I have a Company class which has a collection of Employees. The Employee class also has a Company property.

我希望能够对 Company 进行序列化,并将员工列表包含在序列化中.

I would like to be able to serialize a Company and include the list of employees in the serialization.

这是公司:

public class Company
{
public long Id { get; set; }
public string Name { get; set; }
public DateTime? Established { get; set; }

public virtual IList<Employee> Employees { get; set; }

public DateTime? DateCreated { get; set; }
public DateTime? DateUpdated { get; set; }
}

这里是员工

public class Employee
{
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }

public virtual Company Company { get; set; }

public DateTime? DateCreated { get; set; }
public DateTime? DateUpdated { get; set; }
}

当我尝试序列化 Company 对象时,出现序列化异常检测到类型的自引用循环".

I get a serialization Exception "Self referencing loop detected for type" when I try to serialize a Company object.

谢谢.

推荐答案

我认为他们已经在最新版本中修复了这个问题.

I think they have fixed this in the latest version.

查看序列化和反序列化"部分下的帮助文档JSON -> 序列化和保留对象引用".

Check out the help docs under the section "Serializing and Deserializing JSON -> Serialization and Preserving Object References".

在初始化 JSON.Net Serializer 时设置此设置:

Set this setting when initializing the JSON.Net Serializer:

PreserveReferencesHandling = PreserveReferencesHandling.Objects;

所以一个例子是这样的:

So an example would be this:

var serializerSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects };

string json = JsonConvert.SerializeObject(people, Formatting.Indented, serializerSettings);

我验证了这适用于我的代码优先解决方案以及导航属性中的循环引用.如果您查看生成的 JSON,它应该到处都有$id"和$ref"属性.

I verified that this works with my code first solution, and a circular reference in the navigation properties. If you look at the resulting JSON it should have "$id" and "$ref" properties everywhere.

这篇关于在 Json.net 中序列化一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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