diff --git a/Src/Doc/ContractResolver.html b/Src/Doc/ContractResolver.html new file mode 100644 index 00000000..c8493d32 --- /dev/null +++ b/Src/Doc/ContractResolver.html @@ -0,0 +1,92 @@ + + + + Contract Resolver + + + + + + +
+ Json.NET - Quick Starts & API Documentation
+ Contract Resolvers
+ +
+ + + +

The IContractResolver interface provides a way to customize how the JsonSerializer serializes and deserializes .NET objects to JSON.

+

Implementing the IContractResolver interface and then assigning an instance to a JsonSerializer lets you control + whether the object is serialized as a JSON object or JSON array, what object members should be serialized, how they are serialized and what they are called.

+ +

DefaultContractResolver

+

The DefaultContractResolver is the default resolver used by the serializer. It provides many avenues of extensibility in the form of virtual methods that can be overriden.

+ +

CamelCasePropertyNamesContractResolver

+

CamelCasePropertyNamesContractResolver inherits from DefaultContractResolver and simply overrides the JSON property name to be written in camelcase.

+ +
Product product = new Product
+ +
                    {
+ +
                      ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
+ +
                      Name = "Widget",
+ +
                      Price = 9.99m,
+ +
                      Sizes = new[] {"Small", "Medium", "Large"}
+ +
                    };
+ +
 
+ +
string json = 
+ +
  JsonConvert.SerializeObject(
+ +
    product,
+ +
    Formatting.Indented,
+ +
    new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
+ +
  );
+ +
 
+ +
//{
+ +
//  "name": "Widget",
+ +
//  "expiryDate": "\/Date(1292868060000)\/",
+ +
//  "price": 9.99,
+ +
//  "sizes": [
+ +
//    "Small",
+ +
//    "Medium",
+ +
//    "Large"
+ +
//  ]
+ +
//}
+
+
+
+ + + +
+ + + + \ No newline at end of file diff --git a/Src/Doc/PreserveObjectReferences.html b/Src/Doc/PreserveObjectReferences.html index 1cff2df3..f8be91c5 100644 --- a/Src/Doc/PreserveObjectReferences.html +++ b/Src/Doc/PreserveObjectReferences.html @@ -1,7 +1,7 @@ - Serializing and deserializing JSON + Serialization and Preserving Object References @@ -10,202 +10,118 @@
Json.NET - Quick Starts & API Documentation
- Serialization and PreserveObjectRefences
+ Serialization and Preserving Object References
-

The quickest method of converting between JSON text and a .NET object is using - the JsonSerializer. The JsonSerializer converts .NET objects into their JSON - equivalent and back again.

+

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.

- -

For simple scenarios the SerializeObject and DeserializeObject methods on JsonConvert provide an easy to use wrapper over - JsonSerializer.

- - -
- -
-
Product product = new Product();
-
 
-
product.Name = "Apple";
-
product.Expiry = new DateTime(2008, 12, 28);
-
product.Price = 3.99M;
-
product.Sizes = new string[] { "Small", "Medium", "Large" };
-
 
-
string output = JsonConvert.SerializeObject(product);
-
//{
-
//  "Name": "Apple",
-
//  "Expiry": "\/Date(1230375600000+1300)\/",
-
//  "Price": 3.99,
-
//  "Sizes": [
-
//    "Small",
-
//    "Medium",
-
//    "Large"
-
//  ]
-
//}
-
 
-
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);
-
- -
- -

JsonSerializer

- - -

For more control over how an object is serialized the JsonSerializer can be used - directly. The JsonSerializer has a number of properties to control its behaviour - when serializing and deserializing.

- -
- -
-
Product product = new Product();
-
product.Expiry = new DateTime(2008, 12, 28);
-
 
-
JsonSerializer serializer = new JsonSerializer();
-
serializer.Converters.Add(new JavaScriptDateTimeConverter());
-
serializer.NullValueHandling = NullValueHandling.Ignore;
-
 
-
using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
-
using (JsonWriter writer = new JsonTextWriter(sw))
-
{
-
  serializer.Serialize(writer, product);
-
  // {"Expiry":new Date(1230375600000),"Price":0}
-
}
-
- -
- -
ReferenceLoopHandling
-

Controls how circular referencing objects are serialized. Error, ignore or - serialize.

-
MissingMemberHandling
-

Controls how missing members (e.g. JSON contains a property that isn't a member - on the object) are handled during deserialization. Ignore or error.

-
NullValueHandling
-

Controls how null values are handled during serialization and deserialization. - Include or ignore.

-
DefaultValueHandling
-

Controls whether a value will be written to JSON or not if it matches the value specified in -the member's DefaultValueAttribute. Include or ignore.

-
ObjectCreationHandling
-

Controls how objects are created during deserialization. Auto, reuse, replace.

-
Converters
-

A collection of JsonConverters that will be used during serialization and - deserialization.

-
TypeNameHandling
-

Controls how .NET type names are used when serializing and deserializing JSON. If - type names are SDFSDFSDF

-

Serialization Attributes

-

There are a number of attributes that can be placed on a class to control how it is serialized.

-

Note that as well as using the built-in Json.NET attributes, Json.NET also looks for the - DataContract and - DataMember attributes when determining how JSON is to be serialized and deserialized. If both are present the Json.NET serialization attributes take precedence.

-
-
[JsonObject(MemberSerialization.OptIn)]
-
public class Person
-
{
-
  // "John Smith"
-
  [JsonProperty]
-
  public string Name { get; set; }
-
 
-
  // "2000-12-15T22:11:03"
-
  [JsonProperty]
-
  [JsonConverter(typeof(IsoDateTimeConverter))]
-
  public DateTime BirthDate { get; set; }
-
 
-
  // new Date(976918263055)
-
  [JsonProperty]
-
  [JsonConverter(typeof(JavaScriptDateTimeConverter))]
-
  public DateTime LastModified { get; set; }
-
 
-
  // not serialized
-
  public string Department { get; set; }
-
}
-
- -
- -
JsonObjectAttribute
-

The MemberSerialization flag on this attribute specifies whether member serialization is opt-in (a member must have the JsonProperty or DataMember attribute to be serialized) or opt-out (everything is serialized by default but can be ignored with the JsonIgnoreAttribute).

-

.NET classes that implement IEnumerable are automatically serialized as an array, populated with the IEnumerable values. Placing the JsonPropertyAttribute will override this and force the serializer to serialize the class's fields and properties.

-
JsonPropertyAttribute
-

Allows the name of the serialized member to be customized. The attribute also indicates that a member should be serialized when member serialization is set to opt-in.

-
JsonIgnoreAttribute
-

Excludes a field or property from serialization.

-
JsonConverterAttribute
-

The JsonConverterAttribute specifies which JsonSerializer is used to convert an object.

-

The attribute can be placed on a class or a member. When placed on a class the JsonConverter - specified by the attribute will be the default way of serializing that class. When the attribute is on a field -or property then the specified JsonConverter will always be used to serialize that value.

-

The priority of which JsonConverter is used is member attribute then class attribute and -finally any converters passed to the JsonSerializer.

- -
-
-
public class MemberConverterClass
-
{
-
  public DateTime DefaultConverter { get; set; }
-
  [JsonConverter(typeof(IsoDateTimeConverter))]
-
  public DateTime MemberConverter { get; set; }
-
}
-
-
-

This example shows the JsonConverterAttribute being applied to a property.

- - -
-
-
DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
-
 
-
MemberConverterClass c = new MemberConverterClass
+
Person p = new Person
  {
-
    DefaultConverter = date,
-
    MemberConverter = date
+
    BirthDate = new DateTime(1980, 12, 23, 0, 0, 0, DateTimeKind.Utc),
+
    LastModified = new DateTime(2009, 2, 20, 12, 59, 21, DateTimeKind.Utc),
+
    Name = "James"
  };
 
-
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
+
List<Person> people = new List<Person>();
+
people.Add(p);
+
people.Add(p);
 
-
Console.WriteLine(json);
-
//{
-
//  "DefaultConverter": "\/Date(0)\/",
-
//  "MemberConverter": "1970-01-01T00:00:00Z"
-
//}
+
string json = JsonConvert.SerializeObject(people, Formatting.Indented);
+
//[
+
//  {
+
//    "Name": "James",
+
//    "BirthDate": "\/Date(346377600000)\/",
+
//    "LastModified": "\/Date(1235134761000)\/"
+
//  },
+
//  {
+
//    "Name": "James",
+
//    "BirthDate": "\/Date(346377600000)\/",
+
//    "LastModified": "\/Date(1235134761000)\/"
+
//  }
+
//]
+
+
+

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 returned list would contain two + completely seperate Person objects with the same values. Writing references by value will also cause problems on objects where a + circular reference occurs.

+ +

PreserveReferencesHandling

+

Settings PreserveReferencesHandling will track object references when serializing + and deserializing JSON.

+ +
+
+
string json = JsonConvert.SerializeObject(people, Formatting.Indented,
+
  new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
+
//[
+
//  {
+
//    "$id": "1",
+
//    "Name": "James",
+
//    "BirthDate": "\/Date(346377600000)\/",
+
//    "LastModified": "\/Date(1235134761000)\/"
+
//  },
+
//  {
+
//    "$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
+
+
+ +

Now only one Person object is created and the deserialized list contains two references to it, mirroring what serialized.

+ +

IsReference on JsonObjectAttribute, JsonArrayAttribute and JsonPropertyAttribute

+ + +

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 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.

+ +
+ +
+
[JsonObject(IsReference = true)]
+
public class EmployeeReference
+
{
+
  public string Name { get; set; }
+
  public EmployeeReference Manager { get; set; }
+
}
+

IReferenceResolver

+

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

-

JsonConverters

-

JsonConverters allows JSON to be manually written during serialization and read during deserialization. This is useful for particularly complex JSON structures or for when you want to change how a type is serialized.

-

To create your own custom converter inherit from the JsonConverter class. Json.NET also comes with a number of JsonConverters:

- - - -
DateTime JSON Converters
-

Json.NET comes with a number of JsonConverters for serializing and deserializing DateTimes. Read - more about dates and Json.NET here.

- -
XmlNodeConverter
-

Converts an XmlNode to and from JSON. Note that to convert a JSON object it must have only a single property - or you must define a root node name to be inserted when using this converter. This is required because properties are converted into nodes and - well formed XML can only have one root node.

- - -
BinaryConverter
-

Converts binary data like a byte array or SqlBinary object to JSON. The binary - data is written as a string in JSON and is encoded in Base64.

- -
CustomCreationConverter
-

An abstract JsonConverter for customizing how an object is create during deserialization. - Inherit from this class and implement the Create method with your own code to create and return an object. - The object will then be populated with JSON values by the serializer.

-

A possible example of using this converter would be to call out to a dependency injection framework to resolve what object should be created.

-
-

The Json.NET serializer has a number of advanced options to alter how JSON is serialized and deserialized.

- -

Serialization Callbacks

-

Json.NET supports serialization callback methods. A callback can be used to manipulate an object before and after its serialization and deserialization by the JsonSerializer.

@@ -135,72 +131,6 @@
-

IContractResolver

- -

The IContractResolver interface provides a way to customize how the JsonSerializer serializes and deserializes .NET objects to JSON.

-

Implementing the IContractResolver interface and then assigning an instance to a JsonSerializer lets you control - whether the object is serialized as a JSON object or JSON array, what object members should be serialized, how they are serialized and what they are called.

- -

DefaultContractResolver

-

The DefaultContractResolver is the default resolver used by the serializer. It provides many avenues of extensibility in the form of virtual methods that can be overriden.

- -

CamelCasePropertyNamesContractResolver

-

CamelCasePropertyNamesContractResolver inherits from DefaultContractResolver and simply overrides the JSON property name to be written in camelcase.

- -
Product product = new Product
- -
                    {
- -
                      ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
- -
                      Name = "Widget",
- -
                      Price = 9.99m,
- -
                      Sizes = new[] {"Small", "Medium", "Large"}
- -
                    };
- -
 
- -
string json = 
- -
  JsonConvert.SerializeObject(
- -
    product,
- -
    Formatting.Indented,
- -
    new JsonSerializerSettings { MappingResolver = new CamelCaseMappingResolver() }
- -
  );
- -
 
- -
//{
- -
//  "name": "Widget",
- -
//  "expiryDate": "\/Date(1292868060000)\/",
- -
//  "price": 9.99,
- -
//  "sizes": [
- -
//    "Small",
- -
//    "Medium",
- -
//    "Large"
- -
//  ]
- -
//}
-
-
-
- -