Use C# to get JSON data from the web url and map it to .NET Class

//Call this function where u want
public void GetSubscription()
{
string requestUrl = ” Url from which u want result”;
// Send the request with url
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);

//Response coming
HttpWebResponse responce = (HttpWebResponse)request.GetResponse();
// var resstream = responce.GetResponseStream();
Stream responseStream = responce.GetResponseStream();

StreamReader responseReader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
JavaScriptSerializer js = new JavaScriptSerializer();

var objText = responseReader.ReadToEnd();

//Result of Json Response Look Like {“id”:1,”name”:Abdul}
//Geting data in List Class after deserialize
GetAllData<Info> myojb = (GetAllData<Info>)js.Deserialize(objText, typeof(GetAllData<Info>));

//Create data table to convert data in table format
DataTable dt = new DataTable();
DataRow dr = null;

//define the columns with data type
dt.Columns.Add(new DataColumn(“ID”, typeof(string)));
dt.Columns.Add(new DataColumn(“Name”, typeof(string)));

foreach (Info objInfo in myojb.data)
{
//creating new row
dr = dt.NewRow();

//add values to each rows
dr[“ID”] = objInfo.id;
dr[“Name”] = objInfo.name;

//add the row to DataTable
dt.Rows.Add(dr);
}
//Bind data table in GridView
GridView1.DataSource = dt;
GridView1.DataBind();

}

//Class for getting all record
public class GetAllData<T>
{
public int total { get; set; }
public int count { get; set; }
public List<T> data { get; set; }
}

//This Class is used for geting record by field and the field name should be same as response name
public class Info
{
public string id { get; set; }
public string name { get; set; }

}

Show 1 Comment

1 Comment

Leave a Reply