Saturday, July 10, 2021

ASP.Net JSON response from REST using C#

 ASP.Net JSON response from REST using C#

In this article I will explain with an example, how to get JSON response from REST API in ASP.Net using C# and VB.Net.

The JSON response from the REST API will be read using WebClient class in ASP.Net using C# and VB.Net.

Download JSON.Net library

The JSON.Net library is available for download from the following URL.

Download JSON.Net

The JSON string returned from the API

The following JSON string is returned from the Snippets Test API.

[

   {

      "CustomerId":1,

      "Name":"John Hammond",

      "Country":"United States"

   },

   {

      "CustomerId":2,

      "Name":"Mudassar Khan",

      "Country":"India"

   },

   {

      "CustomerId":3,

      "Name":"Suzanne Mathews",

      "Country":"France"

   },

   {

      "CustomerId":4,

      "Name":"Robert Schidner",

      "Country":"Russia"

   }

]

HTML Markup

The following HTML Markup consists of an ASP.Net GridView control.

<asp:GridView ID="GridView1" runat="server">

</asp:GridView>

Namespaces

You will need to import the following namespaces.

C#

using System.Net;

using System.Data;

using Newtonsoft.Json;

VB.Net

Imports System.Net

Imports System.Data

Imports Newtonsoft.Json

Get JSON response from REST API in ASP.Net

Inside the Page Load event, first the JSON string is downloaded from an API using DownloadString method of the WebClient class and converted to DataTable using JSON.Net library.

Finally, the DataTable is used to populate the GridView control in ASP.Net using C# and VB.Net.

C#

protected void Page_Load(object sender, EventArgs e)

{

    if (!this.IsPostBack)

    {

        ServicePointManager.Expect100Continue = true;

        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

        string json = (new WebClient()).DownloadString("https://baladotnetblog.blogspot.com/asp/test/master/Customers.json");

        GridView1.DataSource = JsonConvert.DeserializeObject<DataTable>(json);

        GridView1.DataBind();

    }

}

VB.Net

Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgsHandles Me.Load

    If Not Me.IsPostBack Then

        ServicePointManager.Expect100Continue = True

        ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)

        Dim json As String = (New WebClient).DownloadString("https://baladotnetblog.blogspot.com/asp/test/master/Customers.json")

        GridView1.DataSource = JsonConvert.DeserializeObject(Of DataTable)(json)

        GridView1.DataBind()

    End If

End Sub

No comments:

Post a Comment

DotNet Latest Technologies

  I'm not sure exactly what you are looking for or how "recent" the technologies that you might wan to look into are, but I...