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, 4:30 AM
How to consume it? Because its return type is void ?
kalpesh shahPosted Nov 2, 2018, 1:38 AM
How to consume this, since there is no return type to the web method. (Context.Response.Write(js.Serialize(objstudents)); )
Kuppurasu NagarajPosted Apr 18, 2016, 1:11 PM
Nice Sharing...
Rahul ChavanPosted Apr 18, 2016, 6:57 AM
Nice article
Debasis SahaPosted Apr 17, 2016, 1:18 PM
Good One..
Humayun Kabir MamunPosted Apr 17, 2016, 8:06 AM
Nice...
Rahul Kumar SaxenaPosted Apr 17, 2016, 7:51 AM
Good Show
Pankaj Kumar ChoudharyPosted Apr 17, 2016, 7:35 AM
Nice Share.....
Gowtham RajamanickamPosted Apr 17, 2016, 7:20 AM
Nice one
Vignesh ManiPosted Apr 17, 2016, 7:19 AM
Nice