Friday, May 30, 2008

JSONized query strings

I often have to Response.Redirect to an ASP.NET page that takes a lot of parameters. There are a few ways of doing this. One way might be to invoke the page with a query string that contains the parameters:
Foo.aspx?a=66&b=77

If you think of the query string parameters as bunch of properties on a class then you could easily see how one might author that class to also serialize and deserialize the query string by leveraging StringBuilder.Append or String.Format and String.Split etc etc.

I’ve been working with Microsoft AJAX recently and I'd used the text based JSON serializer a couple of times and it got me thinking about how I might leverage that to serialize my object properties to and from the query string. [The XmlSerializer might seem like another approach, but ASP.NET really doesn’t like angle brackets (even encoded) sent as data in the query string – it barfs in case you were wondering with a ‘that data looks very suspicious’ type message.]

So I decided to give the JSON parser a whirl and it works like a charm. Here’s what my JSON encoded query string looks like:

Foo.aspx?qps={"A":66,"B":77}

Here's the class:


Here's the caller:


Here's the callee:


I *always* wrap the FromJSON call in a try / catch block in case someone tries to send a hacked query string that clearly won’t deserialize.

0 comments: