In this article I will explain with an example, how to bind (populate) GridView using
JSON string in
ASP.Net with C# and VB.Net.
Installing Newtonsoft package using Nuget
JSON File URL
The following
JSON file will be used in this article.
[
{
"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 HTML Markup consists of following control:
GridView – For displaying data.
<asp:GridView ID="gvCustomers" 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
Getting JSON response from REST API in ASP.Net
Inside the Page_Load event handler, first the Security Protocol is set.
Then, the
JSON response is get from the URL using
DownloadString method of the
WebClient class and stored into a string variable.
The returned response is converted to DataTable using Newtonsoft library.
Finally, the DataTable is assigned tit he DataSource property of the GridView and the GridView is populated.
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://raw.githubusercontent.com/aspsnippets/test/master/Customers.json");
gvCustomers.DataSource = JsonConvert.DeserializeObject<DataTable>(json);
gvCustomers.DataBind();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
Dim json As String = (New WebClient).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json")
gvCustomers.DataSource = JsonConvert.DeserializeObject(Of DataTable)(json)
gvCustomers.DataBind()
End If
End Sub
Screenshot
Demo
Downloads