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 that the ASPX application page just returns a json string response. Any ideas?

+7
json ajax
source share
4 answers

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

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

And the url of the Ajax call will look like this:

 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 am using jQuery, so the data: object will be set with:

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

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

 {"d":[3]} 

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

+10
source share

Not an aspx page, but maybe an ashx handler. To simplify this, .NET 3.5 has serialization support for JSON .

+8
source share

Take a look at the JavascriptSerializer class provided by the ASP.NET framework. Typically, you should use this in the page method or WebMethod in the WebService to return an object serialized as JSON.

See the MSDN link here .

+2
source share

I usually use a web service (asmx) with the ScriptService and ScriptManager attribute. There are some minor incompatibilities with some jQuery plugins, but this is not too serious, and I do not need to deal with any kind of manual serialization.

0
source share

All Articles