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;
- }
- }
- ///<summary>
- /// Summary description for TestService
- ///</summary>
- [WebService(Namespace = "http://tempuri.org/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- [System.ComponentModel.ToolboxItem(false)]
- // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
- // [System.Web.Script.Services.ScriptService]
- 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));
- }
- }
- }
- [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Let us check the output of the program.

Click on GetStudents and we get the JSON response from the service.



Nitin BathamPosted Aug 11, 2020, 12:30 AM EDT
How to consume it? Because its return type is void ?
kalpesh shahPosted Nov 1, 2018, 9:38 PM EDT
How to consume this, since there is no return type to the web method. (Context.Response.Write(js.Serialize(objstudents)); )
Kuppurasu NagarajTOP 100Posted Apr 18, 2016, 9:11 AM EDT
Nice Sharing...
Rahul ChavanPosted Apr 18, 2016, 2:57 AM EDT
Nice article
Debasis SahaTOP 100Posted Apr 17, 2016, 9:18 AM EDT
Good One..
Humayun Kabir MamunPosted Apr 17, 2016, 4:06 AM EDT
Nice...
Rahul Kumar SaxenaTOP 100Posted Apr 17, 2016, 3:51 AM EDT
Good Show
Pankaj Kumar ChoudharyTOP 100Posted Apr 17, 2016, 3:35 AM EDT
Nice Share.....
Gowtham RajamanickamTOP 100Posted Apr 17, 2016, 3:20 AM EDT
Nice one
Vignesh ManiTOP 100Posted Apr 17, 2016, 3:19 AM EDT
Nice