Apps

Embrace the JSON standard in your C# code

Looking for a leaner approach than XML for formatting and sending data? Then give JSON and even Json.NET, a tool for working with JSON data within C#, a try.

When XML hit the scene, developers extolled its virtues, because there was finally a way to get rid of older formats like comma-delimited for data interchange. Of course, that never happened, because there still had to be a consensus on how the XML was defined and so forth.

While that is still an issue, JavaScript Object Notation (JSON) has emerged as the XML slayer, billing itself as the fat-free alternative to XML. Here's a closer look at JSON, including a couple ways to use it within C# code.

Do we really need another format?

While you may sigh when presented with another way to format and exchange data, JSON's popularity has exploded across the web. A good example is that Twitter no longer supports XML -- JSON is the preferred format. A key feature of JSON is its lightweight design when compared to XML, resulting in less data to interchange.

JSON data is structured as name/value pairs, which can be compared to objects, records, or collections (hash, lists, etc.), or it is an ordered list of values like you would find with arrays. JSON support was added to the .NET Framework beginning with version 3.5. It is supported by the DataContractJsonSerializer class. Basically, you use this class to serialize data into JSON as well as deserializing JSON data into an instance of a type.

Using this class is best demonstrated with code. First, we begin with the following JSON data.

{

"authorLastName": "Patton",

"authorFirstName": "Tony",

"editorLastName": "Weilage",
"editorFirstName":"Mary",
"siteURL":"http://www.techrepublic.com",

"otherURLs": [

"http://www.cnet.com",

"http://www.download.com"

]

}

As you can see, this is a simple format. Basically, it has five name/value pages for the names and site URL. The final piece is an array of other URLs. This can be translated to the following C# classes with a class for the Article and a class for the other URLs.

using System;

using System.Collections.Generic;

using System.Runtime.Serialization;

[DataContract]

public class Article {

[DataMember(Name = "authorLastName")]

public string AuthorLastName { get; set; }

[DataMember(Name = "authorFirstName")]

public string AuthorFirstName { get; set; }

[DataMember(Name = "editorLastName")]

public string EditorLastName { get; set; }

[DataMember(Name = "editorFirstName")]

public string EditorFirstName { get; set; }

[DataMember(Name = "siteURL")]

public Uri SiteURL {get; set; }

[DataMember(Name = "otherURLs")]

public List<SiteURL> OtherURLs { get; set; }

}

[DataContract]

public class SiteURL {

[DataMember(Name = "address")]

public Uri address { get; set; }

public SiteURL(string pValue) {

this.address = new Uri(pValue);

}  }

With the classes in place, we can easily create a JSON representation of the data using the System.Runtime.Serialization.Json class first available in .NET Framework 3.5, but this code uses .NET Framework 4.5. This example is enclosed in a web page, and the JSON formatted data is sent to the client.

using System;

using System.Collections.Generic;

using System.IO;

using System.Runtime.Serialization.Json;

using System.Text;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page  {

protected void Page_Load(object sender, EventArgs e)  {

Article a = new Article();

a.AuthorFirstName = "Tony";

a.AuthorLastName = "Patton";

a.EditorFirstName = "Mary";

a.EditorLastName = "Weilage";

a.SiteURL = new Uri("http://www.techrepublic.com");

a.OtherURLs = new List<SiteURL>();

a.OtherURLs.Add(new SiteURL("http://www.cnet.com"));

a.OtherURLs.Add(new SiteURL("http://www.download.com"));

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Article));

MemoryStream ms = new MemoryStream();

serializer.WriteObject(ms, a);

Response.Write(Encoding.UTF8.GetString(ms.ToArray()));

} }

The code begins with the creation of the class to contain the data (instance of the previously created Article class). The object is populated with data and serialized via the DataContractJsonSerializer class. It is serialized via a MemoryStream object with its contents displayed in the page. Here is what the data looks like when displayed on the page:

{"authorFirstName":"Tony","authorLastName":"Patton","editorFirstName":"Mary","editorLastName":"Weilage","otherURLs":[{"address":"http:\/\/www.cnet.com\/"},{"address":"http:\/\/www.download.com\/"}],"siteURL":"http:\/\/www.techrepublic.com\/"}

With the data in the basic JSON format, you can easily exchange this with other applications or systems. While these built-in classes are nice, I find it easier to use the Json.NET add-on available via CodePlex or NuGet.

Another approach to JSON data

Json.NET is one of the more popular tools for working with JSON data within C#. You can use it to bind JSON data to a format defined in classes, or you can easily access and work with the data on the fly. The following example demonstrates pulling Twitter data and displaying the results in a web page. The Twitter data is retrieved via their search API (search.twitter.com/search.json) using TechRepublic.com as the search term.

The code references the Json.NET library (using Newtonsoft.Json). Basically, it retrieves JSON data in a string variable (results of a search request). The JsonConvert class is used to parse the results, which can be used to display the data. It parses the JSON into an object that has properties that correspond to names within the JSON data.

using System;

using Newtonsoft.Json;

public partial class _Default : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e)  {

using (var wc = new System.Net.WebClient())  {

string json = wc.DownloadString("http://search.twitter.com/search.json?&q=TechRepublic.com");

dynamic dynJson = JsonConvert.DeserializeObject(json);

foreach (var result in dynJson.results)  {

Response.Write(result.from_user + " --> " + result.to_user + " : " + result.text + "<br>");

}  }  }

The Json.NET library offers a clean approach to consuming JSON data. We can redo the earlier example that used the DataContractJsonSerializer class with Json.NET with this code snippet, which reuses the previously created Article class.

var lstArticles = new System.Collections.Generic.List<Article> {

new Article {

AuthorFirstName = "Tony",

AuthorLastName = "Patton",

EditorFirstName = "Mary",

EditorLastName = "Weilage",

SiteURL = new System.Uri("http://www.techrepublic.com")

} };

var json = Newtonsoft.Json.JsonConvert.SerializeObject(lstArticles, Formatting.Indented);

Json.NET offers a much cleaner and straightforward approach to working with JSON data. These two simple examples only provide a peek at what you can do with it, so please review the Json.NET documentation for more information on what if offers.

Keep your engineering skills up to date by signing up for TechRepublic's free Software Engineer newsletter, delivered each Tuesday.

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

1 comments
mholmes1
mholmes1

Is this a no-brainier for MVC or is Web-forms the tried and true technology to stick with?