-Updated documentation

This commit is contained in:
JamesNK
2011-07-27 05:08:39 +00:00
parent c1cafd078d
commit 588e90a11f
3 changed files with 411 additions and 52 deletions
+228
View File
@@ -0,0 +1,228 @@
<html>
<head>
<title>Customizing JSON serialization with attributes</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
<link href="custom.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<div id="control">
<span class="productTitle">Json.NET - Quick Starts & API Documentation</span><br />
<span class="topicTitle">Serialization Guide</span></div>
<div id="content">
<span style="color: DarkGray"> </span>
<p>The Json.NET serializer can serialize a wide variety of .NET objects. This guide
looks at how it works at a high level and in more detail.</p>
<h3>Summary</h3>
<p>At a high level, the Json.NET serializer will convert primitive .NET values into
primitive JSON values, .NET arrays and collections to JSON arrays and everything
else to JSON objects.</p>
<p>Json.NET will throw an error if it encounters incorrect JSON when deserializing a
value. For example if the serializer encounters a JSON property with an array of
values and the type of matching .NET property is not a collection then an error
will be thrown, and vice-versa. </p>
<h4><strong>Complex Types</strong></h4>
<table class="style1">
<tr>
<td>
.NET</td>
<td>
JSON</td>
</tr>
<tr>
<td>
IList, IEnumerable, IList&lt;T&gt;, Array</td>
<td>
Array</td>
</tr>
<tr>
<td>
IDictionary, IDictionary&lt;TKey,
TValue&gt;</td>
<td>
Object</td>
</tr>
<tr>
<td>
Object
(more detail below)</td>
<td>Object</td>
</tr>
</table>
<h4><strong>Primitive Types</strong></h4>
<table class="style1">
<tr>
<td>
.NET .NET</td>
<td>
JSON</td>
</tr>
<tr>
<td>
String</td>
<td>
String</td>
</tr>
<tr>
<td>
Byte<br />
SByte<br />
UInt16<br />
Int16<br />
UInt32<br />
Int32<br />
UInt64<br />
Int64</td>
<td>
Integer</td>
</tr>
<tr>
<td>
Float<br />
Double<br />
Decimal</td>
<td>
Float</td>
</tr>
<tr>
<td>
Enum</td>
<td>
Integer (can be string with
<a href="html/T_Newtonsoft_Json_Converters_StringEnumConverter.htm">StringEnumConverter</a>)</td>
</tr>
<tr>
<td>
DateTime</td>
<td>
String (<a href="DatesInJSON.html">Serializing Dates in JSON</a>)</td>
</tr>
<tr>
<td>
Byte[]</td>
<td>
String (base 64 encoded)</td>
</tr>
<tr>
<td>
Type</td>
<td>
String (type name)</td>
</tr>
<tr>
<td>
Guid</td>
<td>
String</td>
</tr>
<tr>
<td>
<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx" target="_blank">
TypeConverter</a> (convertible to String)</td>
<td>String</td>
</tr>
</table>
<h3>Breakdown of Type Serialization</h3>
<h4><strong>Objects</strong></h4>
<p>.NET types that don’t fall into any other category listed below (i.e. aren’t
lists, dictionaries, dynamic, implement ISerializable, etc) are serialized as
JSON objects.</p>
<p>By default types are serialized in opt-out mode. What that means is all public
fields and properties with getters are automatically serialized to JSON and
members that shouldn’t be serialized are opted-out using the
JsonIgnoreAttribute. To serialize private members the JsonPropertyAttribute can
be placed on private fields and properties or the DefaultMembersSearchFlags can
be changed on DefaultContractResolver to change how members are serialized on
all types.</p>
<p>Types can also be serialized using opt-in mode. Only fields that have a
JsonPropertyAttribute or DataMemberAttribute on them will be serialized. Opt-in
mode for an object is specified using the JsonObjectAttribute on the class. </p>
<h4><strong>IEnumerable, Lists and Arrays</strong></h4>
<p>.NET lists (types that inherit from IEnumerable) and .NET arrays are converted to
JSON arrays. Because JSON arrays only support a range of values and not
properties, any additional properties and fields declared on .NET collections
are not serialized. In situations where a JSON array is not wanted the
JsonObjectAttribute can be placed on a .NET type that implements IEnumerable to
force the type to be serialized as a JSON object instead.</p>
<p>Note that if TypeNameHandling or PreserveReferencesHandling has been enabled for
JSON arrays on the serializer then JSON arrays are wrapped it a containing
object. The object will have the type name/reference properties and a $values
property which will have the collection data.</p>
<p>When deserializing if a member is typed as the interface IList<T> then it will be
deserialized as a List<T>.</p>
<p>Read more about serializing collections here:
<a href="SerializingCollections.html">Serializing Collections </a></p>
<h4><strong>Dictionarys and Hashtables</strong></h4>
<p>.NET dictionaries (types that inherit from IDictionary) are converted to JSON
objects. Note that only the dictionary name/values will be written to the JSON
object when serializing and properties on the JSON object will be added to the
dictionary’s name/values when deserializing. Additional members on the .NET
dictionary are ignored during serialization.</p>
<p>When deserializing if a member is typed as the interface IDictionary<TKey, Value>
then it will be deserialized as a Dictionary<TKey, TValue>.</p>
<p>Read more about serializing collections here:
<a href="SerializingCollections.html">Serializing Collections</a></p>
<h4><strong>Untyped Objects</strong></h4>
<p>.NET properties on a class that don’t specify a type (i.e. they are just object)
are serialized as usual. When untyped properties are deserialized the serializer
has no way to know what type to create (unless type name handling is enabled and
the JSON contains the type names).</p>
<p>For these untyped properties the Json.NET serializer will read the JSON into LINQ
to JSON objects and set them to the property. </p>
<h4><strong>Dynamic</strong></h4>
<p>.NET dynamic objects (introduced in .NET 4) are serialized as JSON objects. A
property is written for every member name returned by
IDynamicMetaObjectProvider.GetDynamicMemberNames.</p>
<p>When deserializing the serializer first attempts to set JSON property values on a
normal .NET member with the matching name. If no .NET member is found with the
property name then the serializer will call SetMember on the dynamic object.</p>
<p>Because a dynamic property on a class doesn’t specify a type, Json.NET has no way
to know what type to create for it when deserializing (unless type name handling
is enabled and the JSON contains the type name). LINQ to JSON objects will be
created for the JSON. </p>
<h4><strong>ISerializable</strong></h4>
<p>Types that implement ISerializable are serialized as JSON objects. When
serializing only the values returned from ISerializable.GetObjectData are used;
members on the type are ignored. When deserializing the constructor with a
SerializationInfo and StreamingContext is called, passing the JSON object’s
values.</p>
<p>In situations where this behaviour is not wanted the JsonObjectAttribute can be
placed on a .NET type that implements ISerializable to force it to be serialized
as a normal JSON object. </p>
<h4><strong>LINQ to JSON</strong></h4>
<p>LINQ to JSON types (e.g. JObject, JArray) are automatically serialized and
deserialized to their equivalent JSON when encountered by the Json.NET
serializer. </p>
<h4><strong>JsonConverter</strong></h4>
<p>Serialization of values that are convertible by a JsonConverter (i.e. CanConvert
returns true for its type) is completely overridden by the JsonConverter. The
test to see whether a value can be converted by a JsonSerializer takes
precedence over all other tests.</p>
<p>JsonConverters can be defined and specified in a number of places: in an
attribute on a member, in an attribute on a class and added to the
JsonSerializer’s converters collection. The priority of which JsonConverter is
used is the JsonConverter defined by attribute on a member then the
JsonConverter defined by an attribute on a class and finally any converters
passed to the JsonSerializer.</p>
<div id="footer">
</div>
</div>
</body>
</html>
+174
View File
@@ -0,0 +1,174 @@
<html>
<head>
<title>Customizing JSON serialization with attributes</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
<link href="custom.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="control">
<span class="productTitle">Json.NET - Quick Starts & API Documentation</span><br />
<span class="topicTitle">Serialization Settings</span></div>
<div id="content">
<span style="color: DarkGray"> </span>
<p>JsonSerializer has a number of properties on it to customize how it serializes
JSON. These can also be used with the methods on JsonConvert via the
JsonSerializerSettings overloads.</p>
<h3>ReferenceLoopHandling</h3>
<p>ReferenceLoopHandling controls how circular referencing objects, e.g. a Person
object referencing itself via a Manager property, are serialized.</p>
<ul>
<li><strong>Error</strong> - By default Json.NET will error if a reference loop is
encountered (otherwise the serializer will get into an infinite loop).</li>
<li><strong>Ignore</strong> - Json.NET will ignore objects in reference loops and
not serialize them. The first time an object is encountered it will be
serialized as usual but if the object is encountered as a child object of itself
the serializer will skip serializing it.</li>
<li><strong>Serialize</strong> - This option forces Json.NET to serialize objects in
reference loops. This is useful if objects are nested but not indefinitely.
</li>
</ul>
<h3>MissingMemberHandling</h3>
<p>MissingMemberHandling controls how missing members, e.g. JSON contains a property
that isn&#39;t a member on the object, are handled during deserialization.</p>
<ul>
<li><strong>Ignore</strong> - By default Json.NET ignores JSON if there is no field
or property for its value to be set to during deserialization.</li>
<li><strong>Error</strong> - Json.NET errors when there is a missing member during
deserialization </li>
</ul>
<h3>NullValueHandling</h3>
<p>NullValueHandling controls how null values on .NET objects are handled during
serialization and how null values in JSON are handled during deserialization.</p>
<ul>
<li><strong>Include</strong> - By default Json.NET writes null values to JSON when
serializing and sets null values to fields/properties when deserializing.</li>
<li><strong>Ignore</strong> - Json.NET will skip writing JSON properties if the .NET
value is null when serializing and will skip setting fields/properties if the
JSON property is null when deserializing. </li>
</ul>
<h3>
DefaultValueHandling</h3>
<p>
&nbsp;DefaultValueHandling controls how Json.NET uses default values set using the .NET
DefaultValueAttribute when serializing and deserializing.</p>
<ul>
<li><strong>Include</strong> - By default Json.NET will write a field/property value
to JSON when serializing if the value is the same as the field/property’s
default value. The Json.NET deserializer will continue setting a field/property
if the JSON value is the same as the default value.</li>
<li><strong>Ignore</strong> - Json.NET will skip writing a field/property value to
JSON if the value is the same as the field/property’s default value. The
Json.NET deserializer will skip setting a .NET object’s field/property if the
JSON value is the same as the default value. </li>
</ul>
<h3>ObjectCreationHandling</h3>
<p>ObjectCreationHandling controls how objects are created and deserialized to
during deserialization.</p>
<ul>
<li><strong>Auto</strong> - By default Json.NET will attempt to set JSON values onto
existing objects and add JSON values to existing collections during
deserialization.</li>
<li><strong>Reuse</strong> - Same behaviour as auto.</li>
<li><strong>Replace</strong> - Json.NET will always recreate objects and collections
before setting values to them during deserialization. </li>
</ul>
<h3>TypeNameHandling</h3>
<p>TypeNameHandling controls whether Json.NET includes .NET type names during
serialization with a $type property and reads .NET type names from that property
to determine what type to create during deserialization.</p>
<ul>
<li><strong>None</strong> - By default Json.NET does not read or write type names
during deserialization.</li>
<li><strong>Objects</strong> - Json.NET will write and use type names for objects
but not collections.</li>
<li><strong>Arrays</strong> - Json.NET will write and use type names for collections
but not objects.</li>
<li><strong>Auto</strong> - Json.NET will check whether an object/collection matches
its declared property and writes the type name if they do not match, e.g. a
property with a type of Mammal has a derived instance of Dog assigned. Auto will
ensure that type information isn’t lost when serializing/deserializing
automatically without having to write type names for every object.</li>
<li><strong>All</strong> - Json.NET will write and use type names for objects and
collections. </li>
</ul>
<h3>TypeNameAssemblyFormat</h3>
<p>TypeNameAssemblyFormat controls how type names are written during serialization.</p>
<ul>
<li><strong>Simple</strong> - By default Json.NET writes the partial assembly name
with the type, e.g. System.Data.DataSet, System.Data. Note that Silverlight and
Windows Phone are not able to use this format.</li>
<li><strong>Full</strong> - Json.NET will write the full assembly name, including
version number, culture and public key token.</li>
</ul>
<p>Read more about the valid values at
<a href="http://msdn.microsoft.com/en-us/library/tt9xha1h" target="_blank">
FormatterAssemblyStyle</a>. </p>
<h3>Binder</h3>
<p>The serialization binder is used to resolve type names to a .NET type.</p>
<p>Read more about the serialization binder here:
<a href="http://msdn.microsoft.com/en-us/library/ffas09b2" target="_blank">SerializationBinder</a></p>
<h3>ConstructorHandling</h3>
<p>ConstructorHandling controls how constructors are used when initializing objects
during deserialization.</p>
<ul>
<li><strong>Default</strong> - By default Json.NET will first look for a constructor
marked with the JsonConstructorAttribute, then look for a public default
constructor (a constructor that doesn’t take any arguments) and finally check if
the class has a single public constructor with arguments. If the class has
multiple public constructors with arguments an error will be thrown. This can be
fixed by marking one of the constructors with the JsonConstructorAttribute.</li>
<li><strong>AllowNonPublicDefaultConstructor</strong> - Json.NET will fallback to
using a classes private default constructor if available. </li>
</ul>
<h3>Converters</h3>
<p>This is the collection of JsonConverters that will be used during serialization
and deserialization. </p>
<p>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.</p>
<p>When a JsonConverter has been added to a JsonSerializer it will be checked for
every value that is being serialized/deserialized using its CanConvert to see if
it should be used. If CanConvert returns true then the JsonConverter will be
used to read or write the JSON for that value. Note that while a JsonConverter
gives you complete control over that values JSON, many Json.NET serialization
features are no longer available like type name and reference handling.</p>
<p>To create your own custom converter inherit from the JsonConverter class. Read
more about the built-in JsonConverters below:</p>
<ul>
<li><a href="DatesInJSON.html">Serializing Dates in JSON</a></li>
<li><a href="ConvertingJSONandXML.html">Converting between JSON and XML</a></li>
<li><a href="CustomCreationConverter.html">CustomCreationConverter</a></li>
<li><a href="html/T_Newtonsoft_Json_Converters_StringEnumConverter.htm">
StringEnumConverter</a></li>
</ul>
<h3>ContractResolver</h3>
<p>Internally for every .NET type the JsonSerializer will create a contract of how
the type should be serialized and deserialized, based on type metadata and
attributes applied to the class. Specifying a custom IContractResolver allows
the creation of contracts to be customized.</p>
<p>Read more about Contract Resolvers here: <a href="ContractResolver.html">Contract
Resolvers</a></p>
<h3>Error</h3>
<p>The Error event can catch errors during serialization and either handle the event
and continue with serialization or let the error bubble up and be thrown to the
application.</p>
<p>Read more about error handling here: <a href="SerializationErrorHandling.html">
Serialization Error Handling</a></p>
<div id="footer">
</div>
</div>
</body>
</html>
+9 -52
View File
@@ -1,7 +1,7 @@
<html>
<head>
<title>Serializing and deserializing JSON</title>
<title>Serializing and Deserializing JSON</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
<link href="custom.css" rel="stylesheet" type="text/css" />
</head>
@@ -10,7 +10,7 @@
<div id="control">
<span class="productTitle">Json.NET - Quick Starts & API Documentation</span><br />
<span class="topicTitle">Serializing and deserializing JSON</span></div>
<span class="topicTitle">Serializing and Deserializing JSON</span></div>
<div id="content">
<span style="color: DarkGray"> </span>
@@ -51,6 +51,11 @@
</div></div>
<p>
SerializeObject and DeserializeObject both have overloads that take a
<a href="html/T_Newtonsoft_Json_JsonSerializerSettings.htm">JsonSerializerSettings</a> object. JsonSerializerSettings lets you use many of the JsonSerializer settings listed below while still using the simple serialization methods.
</p>
<h3>JsonSerializer</h3>
@@ -83,56 +88,8 @@
<p>JsonSerializer has a number of properties on it to customize how it serializes JSON.
These can also be used with the methods on JsonConvert via the
JsonSerializerSettings overloads.</p>
<h5>ReferenceLoopHandling</h5>
<p>Controls how circular referencing objects are serialized. Error, ignore or
serialize.</p>
<h5>MissingMemberHandling</h5>
<p>Controls how missing members (e.g. JSON contains a property that isn&#39;t a member
on the object) are handled during deserialization. Ignore or error.</p>
<h5>NullValueHandling</h5>
<p>Controls how null values are handled during serialization and deserialization.
Include or ignore.</p>
<h5>DefaultValueHandling</h5>
<p>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.</p>
<h5>ObjectCreationHandling</h5>
<p>Controls how objects are created during deserialization. Auto, reuse, replace.</p>
<h5>TypeNameHandling</h5>
<p>Controls whether .NET type names are included in serialized JSON and read during deserialization when creating objects. None, Objects, Arrays or All.</p>
<h5>ConstructorHandling</h5>
<p>Controls how constructors are used when initializing objects during deserialization. Default or AllowNonPublicDefaultConstructor.</p>
<h5>Converters</h5>
<p>A collection of JsonConverters that will be used during serialization and
deserialization.</p>
<h3>JsonConverters</h3>
<p>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.</p>
<p>To create your own custom converter inherit from the JsonConverter class. Json.NET also comes with a number of JsonConverters:</p>
<h5>DateTime JSON Converters</h5>
<p>Json.NET comes with a number of JsonConverters for serializing and deserializing DateTimes. Read
more about dates and Json.NET <a href="DatesInJSON.html">here</a>.</p>
<h5>XmlNodeConverter</h5>
<p>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. XmlNodeConverter has an option to
insert a root node for you.</p>
<h5>BinaryConverter</h5>
<p>Converts binary data like the SqlBinary object to JSON. The binary
data is written as a string in JSON and is encoded in Base64.</p>
<h5>CustomCreationConverter</h5>
<p>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.</p>
<p>A possible example of using this converter would be to call out to a dependency injection framework to resolve what object should be created.</p>
<p>Read more about the available JsonSerializer settings here:
<a href="SerializationSettings.html">Serialization Settings</a></p>
<div id="footer">