I hope the basics of web service are clear by now. As we all know Web Service returns XML output by default. But that can be pretty heavy depending upon the data and as the number of hits increases with lots of data the efficiency of the data transfer decreases. JSON as we know is Javascript Object Notation and is very lightweight and has gained a good momentum to use in such scenarios. Developers now prefer JSON over XML response in a Web Service.
Let us create a web Service and see how to return a JSON response from the same.
Open Visual Studio. Create an application. Add Web Service to it. Add the following code in the code behind file of the service.
- using System.Web.Script.Serialization;
- using System.Web.Script.Services;
- using System.Web.Services;
- namespace WebServiceXMLtoJSON
- {
- public class Students
- {
- public int StudentId
- {
- get;
- set;
- }
- public string Name
- {
- get;
- set;
- }
- public int Marks {
- get;
- set;
- }
- }
-
-
-
- [WebService(Namespace = "http://tempuri.org/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- [System.ComponentModel.ToolboxItem(false)]
-
-
- public class TestService: System.Web.Services.WebService
- {
- [WebMethod]
- [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
- public void GetStudents()
- {
- Students[] obj students = new Students[]
- {
- new Students()
- {
- StudentId = 1,
- Name = "NitinTyagi",
- Marks = 400
- },
- new Students()
- {
- StudentId = 2,
- Name = "AshishTripathi",
- Marks = 500
- }
- };
- JavaScriptSerializerjs = newJavaScriptSerializer();
- Context.Response.Write(js.Serialize(objstudents));
- }
- }
- }
We have defined a Students class and populated some data in the GetStudents() webmethod. Have a look closely we have used the following attribute as the response format because we need JSON format.
- [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
We need to serialize the data by JavaScriptSerializer class. We have created an object of JavaScriptSerializer class and used the serialize method which serializes the data.
Let us check the output of the program.
Click on GetStudents and we get the JSON response from the service.
We have successfully generated JSON response from a web service.
Read more articles on ASP.NET: