Click or drag to resize
Json.NETPreserveReferencesHandling setting
 

This sample shows how the PreserveReferencesHandling setting can be used to serialize values by reference instead of by value.

Sample
Types
 1public class Directory
 2{
 3    public string Name { get; set; }
 4    public Directory Parent { get; set; }
 5    public IList<File> Files { get; set; }
 6}
 7
 8public class File
 9{
10    public string Name { get; set; }
11    public Directory Parent { get; set; }
12}
Usage
 1Directory root = new Directory { Name = "Root" };
 2Directory documents = new Directory { Name = "My Documents", Parent = root };
 3
 4File file = new File { Name = "ImportantLegalDocument.docx", Parent = documents };
 5
 6documents.Files = new List<File> { file };
 7
 8try
 9{
10    JsonConvert.SerializeObject(documents, Formatting.Indented);
11}
12catch (JsonSerializationException)
13{
14    // Self referencing loop detected for property 'Parent' with type
15    // 'Newtonsoft.Json.Tests.Documentation.Examples.ReferenceLoopHandlingObject+Directory'. Path 'Files[0]'.
16}
17
18string preserveReferenacesAll = JsonConvert.SerializeObject(documents, Formatting.Indented, new JsonSerializerSettings
19{
20    PreserveReferencesHandling = PreserveReferencesHandling.All
21});
22
23Console.WriteLine(preserveReferenacesAll);
24// {
25//   "$id": "1",
26//   "Name": "My Documents",
27//   "Parent": {
28//     "$id": "2",
29//     "Name": "Root",
30//     "Parent": null,
31//     "Files": null
32//   },
33//   "Files": {
34//     "$id": "3",
35//     "$values": [
36//       {
37//         "$id": "4",
38//         "Name": "ImportantLegalDocument.docx",
39//         "Parent": {
40//           "$ref": "1"
41//         }
42//       }
43//     ]
44//   }
45// }
46
47string preserveReferenacesObjects = JsonConvert.SerializeObject(documents, Formatting.Indented, new JsonSerializerSettings
48{
49    PreserveReferencesHandling = PreserveReferencesHandling.Objects
50});
51
52Console.WriteLine(preserveReferenacesObjects);
53// {
54//   "$id": "1",
55//   "Name": "My Documents",
56//   "Parent": {
57//     "$id": "2",
58//     "Name": "Root",
59//     "Parent": null,
60//     "Files": null
61//   },
62//   "Files": [
63//     {
64//       "$id": "3",
65//       "Name": "ImportantLegalDocument.docx",
66//       "Parent": {
67//         "$ref": "1"
68//       }
69//     }
70//   ]
71// }