Saturday, July 7, 2012

Handling JSON in .Net/C#


XML is used as the native data representation in the .Net world.  Yet JSON, "The Fat-Free Alternative to XML" (quote from http://www.json.org/xml.html), is winning hearts and minds of many web developers.  If you're relying on some public web services like we do on Twitter APIs, chances are you'd need to use JSON as the data exchange format (Twitter dropped its support for XML not long ago).  This post explores how you can handle JSON effectively in your .Net/C# code.

1. Pick a Json library:
It is tedious and unnecessary to parse Json string yourself if you're just building an app or a website. You can leverage some of the existing Json libraries. Sagi did some perf test and published the following perf comparison chart at his blog. We chose Json.Net because of its being open-source, performance and popularity.

 Parsing Twitter JSON: Comparing C# libraries performance
2. Deserialize Json string to C# class
Before you can do something interesting with Json, you need to deserialize it into a C# object.

First step of serialization is to define your C# class. If you are dealing with complex Json structure, http://json2csharp.com/ can help you generate C# class signature automatically.

Once you have the class, you may
1) Deserialize the entire Json string by using the ReadObject method of the DataContractJsonSerializer. MSDN provides a couple of quick examples. 

2) If you prefer to customize the deserialization (e.g. you need more granular control at field level), StackOverflow has an good example showing how to do this using Json.Net:

    public class User {
        public User(string json) {
            JObject jObject = JObject.Parse(json);
            JToken jUser = jObject["user"];
            name = (string) jUser["name"];
            teamname = (string) jUser["teamname"];
            email = (string) jUser["email"];
            players = jUser["players"].ToArray();
        }

        public string name { get; set; }
        public string teamname { get; set; }
        public string email { get; set; }
        public Array players { get; set; }
    }

In either case, there is one caveat -- the DateTime field often needs special handling.  Json represents DateTime as string, which may or may not be in the format that can be recognized by .Net's DateTime parser.  When it is not, it may fail the entire deserialization. 

For example, date/time fields in Twitter's Json responses are in the following format:
    Sat Jul 07 22:21:50 +0000 2012

To convert that into a proper C# DateTime object, you need to explicitly specify the format for the .Net parser:

public const string Const_TwitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";

DateTime createdAt = DateTime.ParseExact((string)jo["created_at"], Const_TwitterDateTemplate, new System.Globalization.CultureInfo("en-US"));

3. Return Json from an Asp.Net MVC method
One big benefit of returning a Json object from your Asp.Net application is that it can be consumed natively by jQuery Ajax. For example,

$.ajax({
    url: '/Customer/GetCustomerInJson',
    dataType: "json",
    success: function (data) {
        alert(data.name);
    }
});

If you want to return a native C# object in Json format, you can use Controller.Json method in your controller.
public class Customer
{
    public string name { getset; }
    public string country { getset; }
}

public ActionResult GetCustomerJson()
{
    Customer newCustomer = new Customer() { name = "John Doe", country = "USA" };
    return Json(newCustomer);
}

If you already have a Json string that you obtain from somewhere else (function/API call,  database etc.), you can just return a Content result with application/json content type.

        public ActionResult GetCustomerJson()
        {
            string jsonString = string.Empty;

            // TODO: Get json string somewhere

            return Content(jsonString, "application/json");
        }



No comments:

Post a Comment