Convert .NET Objects To JSON

Say you have a class you’ve implemented for use in your server code but it would be really handy to write some JavaScript such that you can extend some of the server object’s functionality onto the client. A growingly popular development trend is to create JavaScript “classes” that communicate with the server with Ajax calls using JavaScript Object Notation, or as it’s commonly known JSON. JSON is a compact way of sending data between JavaScript objects or between the client and server. PHP developers have had utility functions to covert objects into a JSON representation and vice versa for quite some time. And thankfully with version 3.5 of the Microsoft .NET Framework, a utility class call the JavaScriptSerializer is available for us ASP.NET developers.

Using the JavaScriptSerializer is pretty simple for basic data types. Once you have an instance of the object, you can then call the Serialize method passing it the object you want to convert to JSON and it will return a JavaScript representation of that object you can then use on the client’s browser. Take a look at the example below:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Web.Scripts.Serialization" %>
<%
protected string JsonString { get; set; }

protected Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer s = new JavaScriptSerializer();
List<int> list = new List<int>() { 1, 1, 2, 3, 5, 8, 13, 21 };
this.JsonString = s.Serialize(list);
}
%>
<html>
<body>
A number sequence from the server: <span id="sequence"></span>
<script type="text/javascript">
// the JSON returned from the server is [1, 1, 2, 3, 5, 8, 13, 21]
var fromServer = <%=JsonString%>;
document.getElementById("sequence").innerHTML = fromServer.join(", ");
</script>
</body>
</html>

What this page does is load up a list of integers and then calls the Serialize method to create JSON out of that object. The .NET class knows how to serialize basic data types, arrays, lists, dictionaries, etc. The JSON produced by the serialization will represent a ready-to-use array of integers in JavaScript. We can then iterate through that array, use it in our client objects or, like the example above, create a concatenated string to display to the user. While the example doesn’t do a whole lot and probably isn’t the most practical use for the JavaScriptSerializer, it does give you an idea of how you can communicate between server and client.

Related Posts:

This entry was posted in C# and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *