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.