Click here to Skip to main content
Click here to Skip to main content

Handling Generic JSON objects in your WebMethods

, 4 Sep 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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>();
   }	      	
}

License

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

Share

About the Author

Billy S Davis
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? :) PinmemberThomas Warnick6-Sep-11 12:34 
GeneralReason for my vote of 4 Nice quick little review, down to th... PinmemberBrianBissell6-Sep-11 7:41 
GeneralReason for my vote of 5 nice; keep on refactoring : ) PinmemberIlka Guigova1-Sep-11 6:30 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411023.1 | Last Updated 4 Sep 2011
Article Copyright 2011 by Billy S Davis
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid