You don’t need to download or install any external Libraries to serialize/deserialize you Objects to/from JSON. All you need to do is to reference to your project “System.Web.Extensions.dll”.
JSON could be saved in a string object in the following format.
{ "ID": 108, "StartDate": "2011-04-13T15:34:09Z", "Name": "SN1234" }
Now you can easily deserialize the previous JSON string into a Dictionary using the following code
using System.Web.Script.Serialization; var jss = new JavaScriptSerializer(); var dict = jss.Deserialize<Dictionary<string,string>>(jsonText); Console.WriteLine(dict["ID"]); //This will output 108
What if your data are more complex ? for example.
{ "ID": 108, "StartDate": "2011-04-13T15:34:09Z", "Name": "SN1234", "Type": { "ID": 2 "Text": "hello" } }
Deserialization will be like this.
using System.Web.Script.Serialization; var jss = new JavaScriptSerializer(); var dict = jss.Deserialize<Dictionary<string,string>>(jsonText); Console.WriteLine(dict["Type"]["Text"]); //This will output hello
That was how we can easily Deserialize a JSON object. Lets see how we can Serialize to a JSON object.
using System.Web.Script.Serialization; var jss = new JavaScriptSerializer(); var dict = jss.Deserialize<dynamic>(jsonText); var json = jss.Serialize(dict); Console.WriteLine(json);