Click or drag to resize
Json.NETSerializing 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 by mapping the .NET object property names to the JSON property names and copies the values for you.

JsonConvert

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.

Serializing and Deserializing JSON with JsonConvert
 1Product product = new Product();
 2
 3product.Name = "Apple";
 4product.ExpiryDate = new DateTime(2008, 12, 28);
 5product.Price = 3.99M;
 6product.Sizes = new string[] { "Small", "Medium", "Large" };
 7
 8string output = JsonConvert.SerializeObject(product);
 9//{
10//  "Name": "Apple",
11//  "ExpiryDate": "2008-12-28T00:00:00",
12//  "Price": 3.99,
13//  "Sizes": [
14//    "Small",
15//    "Medium",
16//    "Large"
17//  ]
18//}
19
20Product 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.

Serializing JSON to a Stream with JsonSerializer
 1Product product = new Product();
 2product.ExpiryDate = new DateTime(2008, 12, 28);
 3
 4JsonSerializer serializer = new JsonSerializer();
 5serializer.Converters.Add(new JavaScriptDateTimeConverter());
 6serializer.NullValueHandling = NullValueHandling.Ignore;
 7
 8using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
 9using (JsonWriter writer = new JsonTextWriter(sw))
10{
11    serializer.Serialize(writer, product);
12    // {"ExpiryDate":new Date(1230375600000),"Price":0}
13}

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.

You can read more about the available JsonSerializer settings here: Serialization Settings

See Also