In Json.net, serialize one to many relationships.

ef-code-first entity-framework json.net serialization

Question

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.

Here is Company:

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

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.

Thanks.

1
19
4/24/2011 7:07:00 AM

Popular Answer

I think they have fixed this in the latest version.

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

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

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.

15
4/10/2012 4:16:05 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow