Getting JSON output from ASP.Net WebMethod

Althought ASP.Net Webservice provides a very convenient way to develop a Webservice but it just returns XML. At time we need this webservice to return JSON. Here is a tiny trick that makes an XML based webmethod to rueturn JSON.

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(Description = "To gets a list of available customers")]
    public string GetCustomerList(string strToken)
    {
        try
        {
            SPCustomers objCust = new SPCustomers();
         

            ArrayList arlstCusomers = new ArrayList();
            arlstCusomers = objCust.GetList();

            JavaScriptSerializer js = new JavaScriptSerializer(arlstCusomers);
            string strJson = js.Serialize();
            return strJson;
        }
        catch (Exception)
        {
            throw;
        }
    }

 Here objCust.GetList(strTocken) method is being called that returns an ArrayList filled with the data. We can use simple array as well. In case our method returns Dataset or Datatable we need to convert this to Array or Arraylist in order to make this work. Following is the code snippet that convert the DataTable to Multidimentional Array:

        public string[][] foo(DataTable tblCustomers)
        {

            string[][] multiDimArray = new string[tblCustomers.Rows.Count][];
            int i = 0;
            foreach (DataRow rs in tblCustomers.Rows)
            {
                multiDimArray[i] = new string[] { rs["CustID"].ToString(), rs["Name"].ToString(), rs["Address"].ToString()};
                i = i + 1;
            }
            return multiDimArray;

        }
In the similar fashion one can manuplate the arraylist objects within an ArrayList object and directly serialize it e.g. JavaScriptSerializer js = new JavaScriptSerializer(arlstCusomers);

Hope this helps
Cheers


Comments

Popular posts from this blog

SharePoint 2010 Migration Woes: Importing and exporting lists template between different SP2010 Servers

How to Stop People From Reading Your Mind and Judging You

SPFx: Develop using SharePoint Framework without Installing all the dependecies.