Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Earlier this year, before I learnt about Code Review StackExchange, I gave this answer in response to a question about how to combine ASP.net, jQuery, and JSON: http://stackoverflow.com/questions/5756147/basic-simple-asp-net-jquery-json-example/5756591#5756591

I keep thinking that there must be a better way to handle the JSON than just using escaped string literals, but I'd like to know for sure.

urlToHandler = 'handler.ashx';
jsonData = '{ "dateStamp":"2010/01/01", "stringParam": "hello" }';
$.ajax({
                url: urlToHandler,
                data: jsonData,
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json',
                success: function(data) {                        
                    setAutocompleteData(data.responseDateTime);
                },
                error: function(data, status, jqXHR) {                        
                    alert('There was an error.');
                }
            }); // end $.ajax


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";

        DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]);
        string stringParam = (string)Request.Form["stringParam"];

        // Your logic here

        string json = "{ \"responseDateTime\": \"hello hello there!\" }";
        context.Response.Write(json);    
    }
share|improve this question
    
Thanks for the answer. I was wondering, specifically, if there is a way to improve the client side scripting; a good way to format JSON client side. Supposing that the dateStamp and stringParam values were not hardcoded, but rather read from a web form, the only way I know to build the JSON is string concatenation, and that's no fun and ugly as sin! –  Rice Flour Cookies Jun 30 '11 at 13:45

1 Answer 1

up vote 6 down vote accepted

You are correct. There is a better way. Starting in .NET 3.5, there is a JavaScriptSerializer class that can be used for simplifying JSON responses. It can be found in the System.Web.Script.Serialization namespace (System.Web.Extensions assembly)

First, you'd need to make a model to represent your response:

public class SimpleResponse {
    public string responseDateTime { get; set; }

    public SimpleResponse() {
          responseDateTime = "hello hello there!";
    }
}

...Then in your handler:

 public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "application/json";
     var json = new JavaScriptSerializer();

     context.Response.Write(
         json.Serialize(new SimpleResponse())
     );    
 }

Here is the result:

{"responseDateTime":"hello hello there!"}

In an ASP.NET MVC application this is more trivial. Just return a JsonResult from your controller:

public JsonResult Index()
{
    return Json(new SimpleResponse());
}
share|improve this answer
    
I've learnt that some special steps need to be taken to deal with DateTime JSON serialization. I wrote about it on my personal web site: danielsadventure.info/DotNetDateTime –  Rice Flour Cookies Feb 21 '13 at 23:31

protected by syb0rg Mar 2 at 18:16

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.