C# .NET: Serialize/Deserialize Into JSON data in .NET

9/9/2013 2:58:51 PM

The following code will allow you to serialize and object into a json string and then deserialize the json string back into the object. Two examples are shown, one use the .NET serializer and the other using Newtonsoft.

//Required Reference: System.Web.Extensions

//serialize - .NET Framework
//1. Create serializer
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };
//2. Serialize
string jsonData = serializer.Serialize(objectToSerialize);

//deserialize - .NET Framework
//1. Create serializer
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };
//2. Deserialize
MyObject obj = serializer.Deserialize<MyObject>(jsonData);


//serialize - Newtonsoft
string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(objectToSerialize);

//deserialize - Newtonsoft
MyObject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MyObject>(jsonData);