Click or drag to resize
Json.NETPreserving Object References
 

By default Json.NET will serialize all objects it encounters by value. If a list contains two Person references and both references point to the same object, then the JsonSerializer will write out all the names and values for each reference.

Preserve Object References Off
 1Person p = new Person
 2{
 3    BirthDate = new DateTime(1980, 12, 23, 0, 0, 0, DateTimeKind.Utc),
 4    LastModified = new DateTime(2009, 2, 20, 12, 59, 21, DateTimeKind.Utc),
 5    Name = "James"
 6};
 7
 8List<Person> people = new List<Person>();
 9people.Add(p);
10people.Add(p);
11
12string json = JsonConvert.SerializeObject(people, Formatting.Indented);
13//[
14//  {
15//    "Name": "James",
16//    "BirthDate": "1980-12-23T00:00:00Z",
17//    "LastModified": "2009-02-20T12:59:21Z"
18//  },
19//  {
20//    "Name": "James",
21//    "BirthDate": "1980-12-23T00:00:00Z",
22//    "LastModified": "2009-02-20T12:59:21Z"
23//  }
24//]

In most cases this is the desired result, but in certain scenarios writing the second item in the list as a reference to the first is a better solution. If the above JSON was deserialized now, then the returned list would contain two completely separate Person objects with the same values. Writing references by value will also cause problems on objects where a circular reference occurs.

PreserveReferencesHandling

Setting PreserveReferencesHandling will track object references when serializing and deserializing JSON.

Preserve Object References On
 1string json = JsonConvert.SerializeObject(people, Formatting.Indented,
 2    new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
 3
 4//[
 5//  {
 6//    "$id": "1",
 7//    "Name": "James",
 8//    "BirthDate": "1983-03-08T00:00Z",
 9//    "LastModified": "2012-03-21T05:40Z"
10//  },
11//  {
12//    "$ref": "1"
13//  }
14//]
15
16List<Person> deserializedPeople = JsonConvert.DeserializeObject<List<Person>>(json,
17    new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
18
19Console.WriteLine(deserializedPeople.Count);
20// 2
21
22Person p1 = deserializedPeople[0];
23Person p2 = deserializedPeople[1];
24
25Console.WriteLine(p1.Name);
26// James
27Console.WriteLine(p2.Name);
28// James
29
30bool equal = Object.ReferenceEquals(p1, p2);
31// true

The first Person in the list is serialized with the addition of an object ID. The second Person in JSON is now only a reference to the first.

With PreserveReferencesHandling on, now only one Person object is created on deserialization and the list contains two references to it, mirroring what we started with.

Note Note

References cannot be preserved when a value is set via a non-default constructor. With a non-default constructor, child values must be created before the parent value so they can be passed into the constructor, making tracking reference impossible. ISerializable types are an example of a class whose values are populated with a non-default constructor and won't work with PreserveReferencesHandling.

IsReference

The PreserveReferencesHandling setting on the JsonSerializer will change how all objects are serialized and deserialized. For fine grain control over which objects and members should be serialized as a reference there is the IsReference property on the JsonObjectAttribute, JsonArrayAttribute and JsonPropertyAttribute.

Setting IsReference on JsonObjectAttribute or JsonArrayAttribute to true will mean the JsonSerializer will always serialize the type the attribute is against as a reference. Setting IsReference on the JsonPropertyAttribute to true will serialize only that property as a reference.

IsReference
1[JsonObject(IsReference = true)]
2public class EmployeeReference
3{
4    public string Name { get; set; }
5    public EmployeeReference Manager { get; set; }
6}
IReferenceResolver

To customize how references are generated and resolved the IReferenceResolver interface is available to inherit from and use with the JsonSerializer.

See Also