Monday 13 September 2010

How to pass JSON arrays and other data types to an ASMX web service

Ah interoperability… great fun, great fun.

So jQuery is your new best friend and, along with JSON, there's nuthin' you can't do. The server side stuff is still there in the background and you've got some old school ASP.NET (.asmx) web services hanging around but DOM elements are otherwise flying all over the place, postbacks are just so passé, and even the marketing girls are mildly impressed at your skillz. You're branching out, shifting code and complexity from the server to the browser, and it's time to do some heavier data shunting. Here a few things to know about passing JSON data to an ASMX web service that may help you on your way…

JSON.stringify

Know it, use it, love it. It's part of the JSON2 library and you need it if you don't have it already. Use it to prepare (aka properly encode) your JSON data before sending it off to the big mean ol' web server:

data: {"days": JSON.stringify(["Mon", "Tues"])}

That will encode as &days=["Monday","Tuesday"]

Yeah, I know, it's another file to download but the guy who wrote JSON also wrote this and it can be merged and minified. I've tried writing my own mini-version as a function and while this works for simple strings, save yourself some time when it comes to arrays and the like and just use this sucker.

Arrays

Arrays seem trickier than they should… maybe I'm just a dumb guy—probably. Anyway, you can pass a JSON array to an .asmx web service without much work at all.

The client-side call listed above is everything you need to do from that end. On the server side, create yourself a new web service method with a List<string> parameter:

[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string ConsumeArray (List<string> days)
{…}

That's all there is to it. If you're not passing in strings, declare the List<> parameter with a type of object or something else. You can use .NET arrays in the web method signature as well if you really want (need) to.

Integers

When in doubt, stringify:

data: { "i": JSON.stringify(2) }

An int parameter on the web service end will handle this graciously.

Booleans

The good ol' boolean—a simple concept computer science has managed to bastardise like no other…

When in doubt, stringify:

data: { "b": jsonpEncode("true") }

Like the int parameter, a bool in your web method signature will take care of this.

A brief note: JSON, or rather jQuery's parseJSON function, is a particular beast and doesn't seem to know about anything other than the lower case true and false strings. If, for any reason, you ToString a bool in your .NET web service and try to pass it back, parseJSON will fail. If you forget to brush your teeth in the morning, parseJSON will fail.

Dates

Sorry, on my todo list ;-)

Tools

When working through this stuff, it pays to have Fiddler open to inspect the requests you're sending through and any error messages you're getting back. I find Fiddler sometimes breaks this stuff so try turning off the capture if you're getting weird errors; optionally, revert to Firebug (Firefox only, of course).

Fully decoding the data you sniff from a JSONP request passed along in the query string will require some additional tooling; in short, you'll want to decode the value using a free online tool like Opinionated Geek's URL decoder.

If you found this post helpful, please support my advertisers.

2 comments:

  1. how to deserialize json object or string in asp.net web service and to return string

    ReplyDelete
  2. i hav the json object var model = {"d":[
    {"AttachmentId":263,"FileName":"dummy document 1.docx","DateAdded":"2009-10-06 11:46:12","FileSize":"9,7 KB"},
    {"AttachmentId":264,"FileName":"dummy document 2.docx","DateAdded":"2009-10-07 11:46:12","FileSize":"9,7 KB"},
    {"AttachmentId":265,"FileName":"dummy document 11.docx","DateAdded":"2009-10-08 11:46:12","FileSize":"9,7 KB"},
    {"AttachmentId":266,"FileName":"dummy document 53.docx","DateAdded":"2009-10-09 11:46:12","FileSize":"9,7 KB"},
    {"AttachmentId":271,"FileName":"another dummy document.docx","DateAdded":"2009-10-14 17:14:29","FileSize":"9,7 KB"},
    {"AttachmentId":272,"FileName":"error.png","DateAdded":"2009-10-16 18:58:28","FileSize":"20,9 KB"},
    {"AttachmentId":273,"FileName":"GUI - ugly error message.png","DateAdded":"2009-10-16 19:02:32","FileSize":"13,8 KB"},
    {"AttachmentId":274,"FileName":"message.txt","DateAdded":"2009-10-16 19:09:34","FileSize":"1,5 KB"}
    ]};


    how to send it from client side to asp.net web service and deserialize json object there in web server and return to client side ? please help me

    ReplyDelete

Spam comments will be deleted

Note: only a member of this blog may post a comment.