Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you provide JSON response data in .NET?

Without using any third party tools, what is the ideal way to provide JSON response data?

I was thinking of having an ASPX application page to just return the json string response. Any ideas?

like image 600
LB. Avatar asked May 07 '09 15:05

LB.


3 Answers

The simplest way is to create a method with the [WebMethod] attribute, and the response will automatically be JSON serialized. Try it yourself:

[WebMethod]
public static string GetDateTime()
{
    return DateTime.Now.ToString();
}

And the Ajax call URL would be:

Page.aspx/GetDateTime

Edit:

To pass parameters, just add them to the function:

[WebMethod]
public static int AddNumbers(int n1, int n2)
{
    return n1 + n2;
}

I'm using jQuery so the data: object would be set with:

data: "{n1: 1, n2: 2}",

Also note that the JSON object returned will look like this:

{"d":[3]}

The extra "d" in the data is explained here: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/

like image 80
John Rasch Avatar answered Nov 14 '22 02:11

John Rasch


Not an aspx page, but maybe an ashx handler. To make this easier, .Net 3.5 has serialization support for JSON built in.

like image 30
Joel Coehoorn Avatar answered Nov 14 '22 02:11

Joel Coehoorn


Look into the JavascriptSerializer class that is provided by the ASP.NET framework. Generally you would use this in a Page Method or a WebMethod in a WebService to return an object serialized as JSON.

See the reference on MSDN here.

like image 22
Adam Markowitz Avatar answered Nov 14 '22 02:11

Adam Markowitz