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

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

问题描述

我正在使用实体框架代码进行数据访问,我有一个公司类,其中有一个Employees的集合。 Employee类也有一个公司属性。

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.

我希望能够序列化一个公司,并在序列化中包含员工名单。

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

这里是Employee

Here is Employee

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

我得到一个序列化异常当我检测到自我引用循环检测类型尝试序列化公司对象。

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 - >序列化和保存对象引用部分中的rel =noreferrer>帮助文档

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

在初始化JSON.Net序列化器时设置此设置:

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天全站免登陆