Click here to Skip to main content
15,886,724 members
Articles / Web Development / ASP.NET
Tip/Trick

Handling Generic JSON objects in your WebMethods

Rate me:
Please Sign up or sign in to vote.
4.67/5 (5 votes)
4 Sep 2011CPOL 29.8K   5   3
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:


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

or this:


JavaScript
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).


JavaScript
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.


JavaScript
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.


C#
[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!


C#
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>();
   }	      	
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
I have been an in-house developer in the Telecommunications industry for 14+ years. I originally started out as a c++ programmer, and still have "Mission Critical" c++ code in production. But what I really enjoy is creating web applications using c# and jQuery. I'm fairly new to the world of jQuery. I also maintain some PHP websites and Perl scripts, and do some Linux administration. Basically, I know enough about each programming language to stay in a permanent state of confusion!

Comments and Discussions

 
GeneralReason for my vote of 4 is there any source code? :) Pin
Thomas Warnick6-Sep-11 11:34
Thomas Warnick6-Sep-11 11:34 
GeneralReason for my vote of 4 Nice quick little review, down to th... Pin
BrianBissell6-Sep-11 6:41
BrianBissell6-Sep-11 6:41 
GeneralReason for my vote of 5 nice; keep on refactoring : ) Pin
Ilka Guigova1-Sep-11 5:30
Ilka Guigova1-Sep-11 5:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.