Click or drag to resize
Json.NET

PreserveReferencesHandling Enumeration

 
Specifies reference handling options for the JsonSerializer. Note that references cannot be preserved when a value is set via a non-default constructor such as types that implement ISerializable.

Namespace:  Newtonsoft.Json
Assembly:  Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 11.0.1
Syntax
C#
[FlagsAttribute]
public enum PreserveReferencesHandling
Members
  Member nameValueDescription
None0 Do not preserve references when serializing types.
Objects1 Preserve references when serializing into a JSON object structure.
Arrays2 Preserve references when serializing into a JSON array structure.
All3 Preserve references when serializing.
Examples
Preserve Object References
string json = JsonConvert.SerializeObject(people, Formatting.Indented,
    new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

//[
//  {
//    "$id": "1",
//    "Name": "James",
//    "BirthDate": "1983-03-08T00:00Z",
//    "LastModified": "2012-03-21T05:40Z"
//  },
//  {
//    "$ref": "1"
//  }
//]

List<Person> deserializedPeople = JsonConvert.DeserializeObject<List<Person>>(json,
    new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

Console.WriteLine(deserializedPeople.Count);
// 2

Person p1 = deserializedPeople[0];
Person p2 = deserializedPeople[1];

Console.WriteLine(p1.Name);
// James
Console.WriteLine(p2.Name);
// James

bool equal = Object.ReferenceEquals(p1, p2);
// true
See Also