This article explains how to consume a Web API using a Web Request and deserialize it in JSON and bind data in a grid view.

Getting Started

Create a new project in Visual Studio 2012 and select "Empty ASP.NET Web Application" and click "OK".

First of all, add two classes:

  1. public class wrapper
  2. {
  3. public List<SalesPerson> salesperson { get; set; }
  4. }
  5. public class SalesPerson
  6. {
  7. public String Code { get; set; }
  8. public String databaseID { get; set; }
  9. public String name { get; set; }
  10. public String path { get; set; }
  11. public String definition { get; set; }
  12. }

Now add your web api URL:

  1. string _URL = "https://api.icarol.com/v1/Resource/Taxonomy?db=2285";
Now drag and drop a GridView data control onto the page.

Now add these namespaces:

  1. using System.IO;
  2. using System.Web.Script.Serialization;
  3. protected void Page_Load(object sender, EventArgs e)
  4. {
  5. WebRequest req = WebRequest.Create(_URL);
  6. req.Method = "GET";
  7. req.Headers.Add("key");
  8. req.ContentType = "application/json; charset=utf-8";
  9. WebResponse resp = req.GetResponse();
  10. Stream stream = resp.GetResponseStream();
  11. StreamReader re = new StreamReader(stream);
  12. String json = re.ReadToEnd();
  13. json = "{\"SalesPerson\":" + json + "}";
  14. wrapper w = (wrapper)new JavaScriptSerializer().Deserialize(json, typeof(wrapper));
  15. GridView1.DataSource = w.salesperson;
  16. GridView1.DataBind();
  17. }

GridView

  1. <asp:GridView ID="GridView1" runat="server" Width="500px" CellPadding="4" ForeColor="#333333" GridLines="None" EmptyDataText="Data Not Found">
  2. <AlternatingRowStyle BackColor="White" />
  3. <EditRowStyle BackColor="#7C6F57" />
  4. <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
  5. <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
  6. <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
  7. <RowStyle BackColor="#E3EAEB" />
  8. <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
  9. <SortedAscendingCellStyle BackColor="#F8FAFA" />
  10. <SortedAscendingHeaderStyle BackColor="#246B61" />
  11. <SortedDescendingCellStyle BackColor="#D4DFE1" />
  12. <SortedDescendingHeaderStyle BackColor="#15524A" />
  13. </asp:GridView>

Now run the application to see the output.

img1.jpg

Image 1.