How To Create A JSON Web Service In ASP.NET

ASP.NET makes it easy to create web services but they usually return XML. Like many web developers I now prefer JSON. This article and sample code will show you how to get your web service to return data in the JSON format. The web service is written in C#. Since my web hosting company only provides me with a MySQL database, we’ll make this project a little more challenging by pulling data from a MySQL database. Finally, I will show you how to use jQuery to call your web service. So you get three kinds of value from this article; a web service in C# to return JSON data, how to use a MySQL database, and how to call an ASP.NET web service using jQuery. None of those three tasks are very intuitive or simple when using ASP.NET because they all go against the framework conventions.

The first task to tackle is connecting to the MySQL database. ASP.NET is usually used with SQL Server or SQL Server Express so using MySQL is not always easy. On my local development web server I downloaded the MySQL Connector/ODBC 5.1 from http://dev.mysql.com/downloads/connector/odbc/5.1.html. Then my web.config file merely needed a connection string node:

NOTE: This is not my real password and there is no external access to MySQL server running on my development server.

For this demonstration, I am using a simple database I use to keep track of the books I read. It has a single table “reading” which has only three columns; BookNum, Title, Author. I don’t know if CrystalTech has the MySQL ODBC driver installed, but I was able to create a datasource name using the control panel so the connection string used a “dsn=books” instead of the driver.

The C# code for the web service at http://www.williamsportwebdeveloper.com/BookServices.asmx shows you how an ODBC connection is used to query the MySQL database. What you should notice in the code is that various method attributes are used on the web service class and methods. These method attributes require the System.Web.Script reference. If you get an error concerning missing assemblies then make sure your web.config file has everything it needs for an AJAX enabled ASP.NET site. As you can see, there is a ScriptMethod method attribute that specifies JSON as the response format. The tricky part is converting a dataset into a JSON string. I used a jagged array to accomplish that because it will serialize properly. That is probably the most valuable tip in this entire article.

1:using System;

2:using System.Web;

3:using System.Collections;

4:using System.Web.Services;

5:using System.Web.Services.Protocols;

6:using System.Data;

7:using System.Data.Odbc;

8:using System.Web.Script.Serialization;

9:using System.Web.Script.Services;

10:

11:/// <summary>

12:/// Web services to query the book database. All methods return JSON data.

At this point you have a web service that queries a MySQL database and returns records as JSON data. This is extremely useful if you want to use that data on your home page without making it an ASP.NET page. You can get the data using AJAX and avoid having your home page show an error should your ASP.NET web application develop a problem. Next I will show you the JavaScript code for calling the web service. I’ll use the jQuery library because it is extremely popular with web developers right now. It makes it easy to write JavaScript that works in both browsers but you may not know how to call an ASP.NET web service using jQuery, especially since we need to pass a parameter to the web service methods. This is also tricky because the content type must be JSON.

You can try a working example at: http://www.williamsportwebdeveloper.com/BookQuery.html. This JavaScript is binding function prototypes to the button click events. These functions call the web service methods using the POST method and pass the required parameters as JSON data. The JSON data that it receives in response is used to create a table. You can continue to issue queries without reloading the web page. If you view the source of the BookQuery.html page you will find all the code required for the client page because it does not require any server side code.

46 Responses to How To Create A JSON Web Service In ASP.NET

I prefer JSON when communicating with my web services as well. One difficulty that I encountered is that when the JSON came across the wire it was very difficult to read because it was compressed unlike the XML which was well-formatted. I found a tool called JSON Pro Viewer which helps drastically to view and edit large/deeply nested JSON documents:http://www.jsonpro.com

there are string tag but i want to send only that
[[“1″,”pınar”,”hoşyumruk”,”phosyumruk”,”0033 “],[“2″,”Emre”,”Işın”,”emrei”,”nywmzs “],[“5″,”Ercan”,”Eren”,”eeren”,”7920471 “]] json ,,How can do this please help me it is very important for me please!!!! Anyone can help me to solve this problem????

I’m not getting the example running
I just started VS2008 new website in VB, removed the html, copy pated the example website. Added style.css and jquery-1.3.2.min.js
and nothing happens.
Only the table heading is shown. trying to show an alert in a function does not work either.
Do i miss something?

I have tried your example on my local IIS server. Created two websites – one that hosts the webservice and another that hosts the html that calls the webservice. Works on my local PC. When I move the same setup to my Windows 2008 r2 iis7.5 web server, works as long as I test the html call from the web server. So I know my database connectivity from the web server is working as I get results when I run this from the web server itself…..

When I try to access the webservice from my PC with the webservice hosted on the webserver hosted in the same domain, the results from the db do not show up.

Tried checking calls using Fiddler but did not see any issues. Checked the windows logs on my desktop and the web server and did not see anything recorded. The database binaries installed on the webserver have been given read and execute access to all authenticated users.

There are many programs and hosting companies out there and
it can be very hard to choose which one is best for you and your business.
Therefore, owners should never be put off by a low cost price in assuming
that the hosting service is of poor quality; this is simply not the case
with cloud hosting. While we evaluate a hosting business, it is necessary to identify their services with regard to their performance, reliability, service, scalability and security considerations.