diff --git a/Src/Doc/AdvanceSerializingJSON.html b/Src/Doc/AdvanceSerializingJSON.html index 4db0a917..c481db1c 100644 --- a/Src/Doc/AdvanceSerializingJSON.html +++ b/Src/Doc/AdvanceSerializingJSON.html @@ -17,16 +17,135 @@

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

-

IMappingResolver

+

Serialization Callbacks

-

The IMappingResolver interface provides a way to globally customize how the JsonSerializer maps JSON properties to .NET object members.

-

Implementing the IMappingResolver interface and then assigning an instance to a JsonSerializer lets you control what object members should be serialized, how they are serialized and what they are called.

+

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.

+ +

To tell the serializer which methods should be called during the object's serialization + lifecycle, decorate a method with the appropraite attribute (OnSerializingAttribute, + OnSerializedAttribute, + OnDeserializingAttribute, + OnDeserializedAttribute).

+

Example object with serialization callback methods:

+ +
+
+
public class SerializationEventTestObject
+
{
+
  // This member is serialized and deserialized with no change.
+
  public int Member1 { get; set; }
+
 
+
  // The value of this field is set and reset during and 
+
  // after serialization.
+
  public string Member2 { get; set; }
+
 
+
  // This field is not serialized. The OnDeserializedAttribute 
+
  // is used to set the member value after serialization.
+
  [JsonIgnore]
+
  public string Member3 { get; set; }
+
 
+
  // This field is set to null, but populated after deserialization.
+
  public string Member4 { get; set; }
+
 
+
  public SerializationEventTestObject()
+
  {
+
    Member1 = 11;
+
    Member2 = "Hello World!";
+
    Member3 = "This is a nonserialized value";
+
    Member4 = null;
+
  }
+
 
+
  [OnSerializing]
+
  internal void OnSerializingMethod(StreamingContext context)
+
  {
+
    Member2 = "This value went into the data file during serialization.";
+
  }
+
 
+
  [OnSerialized]
+
  internal void OnSerializedMethod(StreamingContext context)
+
  {
+
    Member2 = "This value was reset after serialization.";
+
  }
+
 
+
  [OnDeserializing]
+
  internal void OnDeserializingMethod(StreamingContext context)
+
  {
+
    Member3 = "This value was set during deserialization";
+
  }
+
 
+
  [OnDeserialized]
+
  internal void OnDeserializedMethod(StreamingContext context)
+
  {
+
    Member4 = "This value was set after deserialization.";
+
  }
+
}
+
+
+ +

The example object being serialized and deserialized by Json.NET:

+ +
+
+
SerializationEventTestObject obj = new SerializationEventTestObject();
+
 
+
Console.WriteLine(obj.Member1);
+
// 11
+
Console.WriteLine(obj.Member2);
+
// Hello World!
+
Console.WriteLine(obj.Member3);
+
// This is a nonserialized value
+
Console.WriteLine(obj.Member4);
+
// null
+
 
+
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
+
// {
+
//   "Member1": 11,
+
//   "Member2": "This value went into the data file during serialization.",
+
//   "Member4": null
+
// }
+
 
+
Console.WriteLine(obj.Member1);
+
// 11
+
Console.WriteLine(obj.Member2);
+
// This value was reset after serialization.
+
Console.WriteLine(obj.Member3);
+
// This is a nonserialized value
+
Console.WriteLine(obj.Member4);
+
// null
+
 
+
obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);
+
 
+
Console.WriteLine(obj.Member1);
+
// 11
+
Console.WriteLine(obj.Member2);
+
// This value went into the data file during serialization.
+
Console.WriteLine(obj.Member3);
+
// This value was set during deserialization
+
Console.WriteLine(obj.Member4);
+
// This value was set after deserialization.
+
+
+ + +

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.

-

DefaultMappingResolver

-

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

+

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.

-

CamelCaseMappingResolver

-

CamelCaseMappingResolver inherits from DefaultMappingResolver and simply overrides the JSON property name to be written in camelcase.

+

CamelCasePropertyNamesContractResolver

+

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

Product product = new Product
diff --git a/Src/Doc/Introduction.html b/Src/Doc/Introduction.html index e7c478c8..e8a0df02 100644 --- a/Src/Doc/Introduction.html +++ b/Src/Doc/Introduction.html @@ -50,7 +50,7 @@

Json.NET is a free open source project that I have developed in my personal time.

- You can show your support for Json.NET by donating. I really appreciate your feedback and support.

+ I really appreciate your feedback and support for Json.NET and its future development.

Donate

diff --git a/Src/Doc/PreserveObjectReferences.html b/Src/Doc/PreserveObjectReferences.html new file mode 100644 index 00000000..1cff2df3 --- /dev/null +++ b/Src/Doc/PreserveObjectReferences.html @@ -0,0 +1,218 @@ + + + + Serializing and deserializing JSON + + + + + + +
+ Json.NET - Quick Starts & API Documentation
+ Serialization and PreserveObjectRefences
+ +
+ + +

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.

+ + +

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
+
  {
+
    DefaultConverter = date,
+
    MemberConverter = date
+
  };
+
 
+
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
+
 
+
Console.WriteLine(json);
+
//{
+
//  "DefaultConverter": "\/Date(0)\/",
+
//  "MemberConverter": "1970-01-01T00:00:00Z"
+
//}
+
+ +
+ +

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.

+ + +
+ + + + \ No newline at end of file diff --git a/Src/Doc/SerializingJSON.html b/Src/Doc/SerializingJSON.html index 75a70f22..5b385969 100644 --- a/Src/Doc/SerializingJSON.html +++ b/Src/Doc/SerializingJSON.html @@ -20,7 +20,7 @@ equivalent and back again.

-

For simple scenarios the SerializeObject and DeserializeObject methods on JavaScriptConvert provide an easy to use wrapper over +

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

@@ -132,7 +132,8 @@ the member's DefaultValueAttribute. Include or ignore.

JsonObjectAttribute
-

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

+

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
@@ -144,8 +145,43 @@ the member's DefaultValueAttribute. Include or ignore.

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
+
  {
+
    DefaultConverter = date,
+
    MemberConverter = date
+
  };
+
 
+
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
+
 
+
Console.WriteLine(json);
+
//{
+
//  "DefaultConverter": "\/Date(0)\/",
+
//  "MemberConverter": "1970-01-01T00:00:00Z"
+
//}
+
+ +
+

JsonConverters

-

JsonConverters allows JSON to be manually be 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.

+

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:

@@ -162,13 +198,13 @@ finally any converters passed to the JsonSerializer.

BinaryConverter

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

+ 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

+

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