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);

SerializeObject and DeserializeObject both have overloads that take a JsonSerializerSettings object. JsonSerializerSettings lets you use many of the JsonSerializer settings listed below while still using the simple serialization methods.

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.

Read more about the available JsonSerializer settings here: Serialization Settings