Saturday, November 20, 2021

Webservice returning JSON sample data in Visual studio asp.net C#

 Webservice code

[WebMethod]

        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

        public void HelloWorld()

        {

            List<Employee> lstEmp = new List<Employee>();

            lstEmp.Add(new Employee() { empName = "yash", empAge = 32, empID = 2 });

            lstEmp.Add(new Employee() { empName = "yash2", empAge = 45, empID = 4 });

            lstEmp.Add(new Employee() { empName = "yash3", empAge = 32, empID = 6 });

            lstEmp.Add(new Employee() { empName = "yash4", empAge = 32, empID = 7 });

            lstEmp.Add(new Employee() { empName = "yash5", empAge = 32, empID = 8 });

            lstEmp.Add(new Employee() { empName = "yash6", empAge = 32, empID = 9 });

            lstEmp.Add(new Employee() { empName = "yash7", empAge = 32, empID = 10 });

            lstEmp.Add(new Employee() { empName = "yash8", empAge = 32, empID = 11 });

            lstEmp.Add(new Employee() { empName = "yash9", empAge = 32, empID = 12 });

            lstEmp.Add(new Employee() { empName = "yash10", empAge = 32, empID = 13 });

            lstEmp.Add(new Employee() { empName = "yash11", empAge = 32, empID = 14 });

            lstEmp.Add(new Employee() { empName = "yash12", empAge = 32, empID = 15 });

            lstEmp.Add(new Employee() { empName = "yash13", empAge = 32, empID = 16 });

            lstEmp.Add(new Employee() { empName = "yash4", empAge = 32, empID = 17 });

            lstEmp.Add(new Employee() { empName = "yash4", empAge = 32, empID = 18 });

            //return lstEmp;

            //return "dfdf";


            JavaScriptSerializer js = new JavaScriptSerializer();

            Context.Response.Write(js.Serialize(lstEmp));

//To desrialize json to list of object, given below

//var deserializedResult = js.Deserialize<List<Employee>>((js.Serialize(lstEmp)));

        }


--------------------------------------------****************------------------------

web.config file code

<configuration>
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</configuration>
----------------------------------************-----------------------------
And type web URL in chrome browser
https://localhost:44396/WebService1.asmx/HelloWorld
(screenshot below)


No comments:

Post a Comment