C#: Useful JSON in .Net
Dec03

C#: Useful JSON in .Net

Welcome to CodeSpread! Why JSON? All web applications revolve around large chunk of data and availability of that data to our application is of utmost importance. To do that, we have options like fetch data from database and sometimes from XMLs. As a result of which we end up hitting DB/File system several times and ultimately compromises with Page speed and performance. JSON- JSON (JavaScript Object Notation) is the solution to avoid all the difficulties with respect to data. Today we will try our hands on using JSON in .Net: The very first thing which is required to use JSON in our code is a namespace. System.Web.Script.Serialization Now the most important class, JavaScriptSerializer Let the play begin: Consider you have a DataTable dt filled with all your DB contents (Columns: UID, Firstname, Lastname, Mobileno, Address and many more) and you need to have these data handy. Then Query this data by linq query.  CODE: var details = from data in dt.AsEnumerable() select new { UID = data.Field("UID"), FirstName = data.Field("FirstName"), LastName  = data.Field("LastName”), Mobileno = data.Field("Mobileno"), Address = data.Field<string>("Address") }; This code has created an anonymous type (Read more about Anonymous type here ) CODE: Now this variable ‘details’ can be serialized to a JSON string as shown below. string JsonString = string.Empty; JavaScriptSerializer jsSerialize = new JavaScriptSerializer(); JsonString = jsSerialize.Serialize(details); //Created above This ‘Jsonstring’ variable will be available to our .aspx (design view) for display or any other operation as per the request The data in the string looks like this: [ { "UID": 1316134065, "Firstname": Jason, "Lastname": "Bourne", "Mobileno": "1234567890", "Address": "XYZ" }, { "UID": 1316134065, "Firstname": Jason, "Lastname": "Bourne", "Mobileno": "1234567890", "Address": "XYZ" } ] On the similar lines, you can do a vice-versa action too. Wondering how? Let’s see how to parse a JSON object using the same class JavaScriptSerializer. Create an instance of JavaScriptSerializer and then call Deserialize function to work on the JSON string which return a Dictionary object Dictionary. CODE: string json = “[{“Firstname”:”Test”, . . . ”; JavaScriptSerializer jsSerialize = new JavaScriptSerializer (); Dictionary dict = jsSerialize.Deserialize(json); Now you have the Dictionary to play around with the data. Enjoy...

Read More