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 by mapping the .NET object property names to the JSON property names and copies the values for you.

JsonConvert - Convert from model to JSON object

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.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "ExpiryDate": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

// Here is how we convert a JSON file into a class model
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.ExpiryDate = 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);
    // {"ExpiryDate":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. You can read more about the available JsonSerializer settings here: Serialization Settings

Last updated