Calling Webservice in C# for JSON Data

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Net;  
  8. using System.Text;  
  9. using System.IO;  
  10. using System.Web.Services;  
  11. using System.Web.Script.Services;  
  12. using System.Web.Script.Serialization;  
  13. using Newtonsoft.Json.Linq;  
  14.   
  15. public partial class _Default : System.Web.UI.Page  
  16. {  
  17.     protected void Page_Load(object sender, EventArgs e)  
  18.     {  
  19.         CallWebService();  
  20.     }  
  21.     private void CallWebService()  
  22.     {  
  23.         StringBuilder str = new StringBuilder();  
  24.         string url = "Put your Service url";  
  25.         WebRequest request = WebRequest.Create(url);  
  26.         using (WebResponse response = (HttpWebResponse)request.GetResponse())  
  27.         {  
  28.             using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))  
  29.             {  
  30.                 string json = reader.ReadToEnd();  
  31.                 var serializer = new JavaScriptSerializer();  
  32.                 var objects = JArray.Parse(json);  
  33.                 str.Append("<table>");  
  34.                 foreach (JObject root in objects)  
  35.                 {  
  36.                     string id = "";  
  37.                     string title = "";  
  38.                     string date = "";  
  39.                     string longdesc = "";  
  40.                       
  41.                     foreach (KeyValuePair<String, JToken> app in root)  
  42.                     {  
  43.                         if (app.Key == "id") id = app.Value.ToString();  
  44.                         if (app.Key == "title") title = app.Value.ToString();  
  45.                         if (app.Key == "date") date = app.Value.ToString();  
  46.                         if (app.Key == "longdesc") longdesc = app.Value.ToString();  
  47.                     }  
  48.                     str.Append("<tr><td><h1>" + title + "</h1></td></tr>");  
  49.                     str.Append("<tr><td>" + date + "</td></tr>");  
  50.                     str.Append("<tr><td>" + longdesc + "</td></tr>");  
  51.                      
  52.                 }  
  53.                 str.Append("</table>");  
  54.                 //---------Social Sharing  
  55.                 divShare.InnerHtml = str.ToString();  
  56.             }  
  57.         }  
  58.     }  
  59. }