65.9K
CodeProject is changing. Read more.
Home

Handling Generic JSON objects in your WebMethods

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (5 votes)

Sep 1, 2011

CPOL
viewsIcon

30290

Wouldn’t it be nice to call your AJAX method and just build a generic object to pass into the server side function, without having to create a bunch of complex server side objects?

So wouldn’t it be nice to call your AJAX method and just build a generic object to pass into the server side function, without having to create a bunch of complex server side objects? Something like:

cd.Methods.ListPeople({ limit: 100, sort: { field: 'age', order: 'asc'} }, OnResults);

or this:

cd.Methods.ListPeople({ limit: 100 }, OnResults);

So the implementation of ListPeople would be like so, notice I’m just passing the object to the server as a string. But I stringify’ed the generic object (don’t forget the single-quotes).

cd.Methods.ListPeople = function (opts, callback) {
    cd.Ajax.Method("ListPeople"
                 , "{'options': '" + JSON.stringify(opts) + "'}"
                 , callback);
};

The implementation of cd.Ajax.Method is just a simple wrapper around the jQuery AJAX call.

cd.Ajax.Method = function (m, d, c) {
	   $.ajax({
           type: "POST"
           , url: "/WebServices/WebMethods.aspx/" + m
           , contentType: "application/json; charset=utf-8"
           , data: d
           , dataType: "json"
           , success: function (msg) { c(msg.d); }
           , error: function (msg) { cd.Ajax.AjaxFailed(msg); }
    });
};

The cd.Methods.ListPeople function will hit the ListPeople server function. Notice I take the options and pass it to my function JsonToDictionary. Then I try to pull the limit variable and the sort dictionary out of the resulting dictionary.

[WebMethod]
public static List<Person> ListPeople( string options )
{
   var opts = JsonToDictionary(options);

   var limit = (opts.ContainsKey("limit")) ? Convert.ToInt32(opts["limit"]) : 0;
   if(opts.ContainsKey("sort"))
   {
      var s = opts["sort"] as Dictionary<string, object>;

      if (s != null)
      {
         var field = (s.ContainsKey("field")) ? s["field"].ToString() : "name";
         var order = (s.ContainsKey("order")) ? s["order"].ToString() : "desc";
         return ListPeopleBll(limit, field, order);
      }
   }

   return  ListPeopleBll(limit);
}

Here is the implementation of JsonToDictionary. Yet again something that I have wasted so much time trying to figure out is actually quite simple. You have to add the using clause for the System.Web.Script.Serialization assembly to get JavaScriptSerializer. Notice that no matter what happens, I will pass a dictionary back and not null. This makes checking for key/value pairs in subsequent code much nicer!

private static Dictionary<string, object> JsonToDictionary(string json)
{
   try
   {
      var js = new JavaScriptSerializer();
      var d = js.Deserialize<Dictionary<string, object>>(json);
      if (d != null)
         return d;
      // I want to return an empty dictionary if the json results in null.
      return new Dictionary<string, object>();
       
   }
   catch
   {
       return new Dictionary<string, object>();
   }	      	
}