Serializing and deserializing JSON

Json.NET

Json.NET - Quick Starts & API Documentation Serializing and deserializing JSON

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 where you want to convert to and from a JSON string 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 is able to read and write JSON text directly to a stream via JsonTextReader and JsonTextWriter. Other kinds of JsonWriters can also be used such as JTokenReader/JTokenWriter to convert your object to and from LINQ to JSON objects or BsonReader/BsonWriter to convert to and from BSON.

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

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.

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.

TypeNameHandling

Controls whether .NET type names are included in serialized JSON and read during deserialization when creating objects. None, Objects, Arrays or All.

ConstructorHandling

Controls how constructors are used when initializing objects during deserialization. Default or AllowNonPublicDefaultConstructor.

Converters

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

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. XmlNodeConverter has an option to insert a root node for you.

BinaryConverter

Converts binary data like the 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.