JavaScriptSerializer example - Read JSON from file and Populate GridView using C# and VB

← PrevNext →

In this tutorial I am going to show you how to read data from a "local JSON file" and bind data to a GridView, without using a framework. For data extraction, I am using JavaScriptSerializer class. The codes are in C# and Visual Basic.

fetch json from file and display in gridview in asp.net

Here's something you should know. In my previous tutorials, I have shared similar examples but using two very different methods. In the first example, I have used a WebGrid in Asp.Net MVC and the second example, I have used a simple HTML table to display JSON data.

Now, if you are looking for a solution in GridView, then its here.

There's one common method that I have used in the previous two and this tutorial is, the JavaScriptSerializer class.

The JSON

First, create a JSON file with some data in it and save the file in your project folder. Here's a sample data.

[
    {
    "ID": "001",
    "Name": "Eurasian Collared-Dove",
    "Type": "Dove" },
  
    {
    "ID": "002",
    "Name": "Bald Eagle",
    "Type": "Hawk" },
  
    {
    "ID": "003",
    "Name": "Cooper's Hawk",
    "Type": "Hawk" },
    {
    "ID": "004",
    "Name": "Bell's Sparrow",
    "Type": "Sparrow" },

    {
    "ID": "005",
    "Name": "Mourning Dove",
    "Type": "Dove"  },

    {
    "ID": "006",
    "Name": "Rock Pigeon",
    "Type": "Dove"  }
]

Or, you can use the data from this page.

The Markup

In the markup section, I have a GridView control, which has not data source (not at design time). We'll bind data to the grid dynamically using Code behind procedure.

<html>
<head runat="server">
    <style>
        .grid { height:100px; width:500px; border:solid 1px #525252; }
        .grid td  
        {
            padding: 2px; 
            border: solid 1px #C1C1C1; 
            color: #333; 
            text-align: center; 
            text-transform: capitalize;
        }
        .grid th  
        {
            padding: 3px; 
            color: #fff; 
            background: #424242 url(grd.png) repeat-x top; 
            border-left: solid 1px #525252; 
            font-size: 16px;
            text-align: center; 
            text-transform: capitalize;
        }        
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="grd" 
                CssClass="grid"
                runat="server"
                AllowPaging="true" 
                PageSize="5"
                OnPageIndexChanging="grd_PageIndexChanging"
               
            </asp:GridView>
        </div>
    </form>
</body>
</html>
C# Code
using System;
using System.Web.UI.WebControls;
using System.Data;      // for DataTable.
using System.IO;
using System.Web.Script.Serialization;      // for JavaScriptSerializer
using System.Collections.Generic;       // for List object.

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack){
            bind_grid_with_json();
        }
    }

    public class birds
    {
        public string ID;
        public string Name;
        public string Type;
    }

    private List<birds> birdsList = new List<birds>();

    private void bind_grid_with_json()
    {
        string sJSON;
        sJSON = Server.MapPath("birds.json");      // The JSON file.

        using (StreamReader sr = new StreamReader(sJSON))
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            birdsList = json.Deserialize<List<birds>>(sr.ReadToEnd());

            DataTable dt = new DataTable();
            {
                dt.Columns.Add("ID", typeof(string));
                dt.Columns.Add("Name", typeof(string));
                dt.Columns.Add("Type", typeof(string));
            }

            foreach (birds val in birdsList)
            {
                DataRow row = dt.NewRow();
                row["ID"] = val.ID; row["Name"] = val.Name; row["Type"] = val.Type;

                dt.Rows.Add(row);
            }

            grd.DataSource = dt;        // assign datatable as datasource to the grid.
            grd.DataBind();
        }
    }

    // for paging.
    protected void grd_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
    {
        grd.PageIndex = e.NewPageIndex;
        bind_grid_with_json();
    }
}

When the page loads, it calls a procedure named "bind_grid_with_json()". This is where it extracts data from local JSON file (birds.json) using StreamReader class.

The JSON is then Deserialized or "converted" (in simple terms) into an object of type T.

Here T can be any type which has properties. Therefore, I am using a List<T> class to store the JSON objects.

See this in the above code... private List<birds> birdsList = new List<birds>();

Finally, I am converting the List (birdsList) to a DataTable, which extract data from the List object and serves the grid with the data.

grd.DataSource = dt;
grd.DataBind();
Visual Basic Code
Option Explicit On

Imports System.Data
Imports System.IO
Imports System.Web.Script.Serialization

Partial Class _Default
    Inherits System.Web.UI.Page

    Dim dPageTotal As Double = 0

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        If Not IsPostBack Then
            Me.bind_grid_with_json()
        End If
    End Sub

    Public Class birds
        Public ID As String
        Public Name As String
        Public Type As String
    End Class

    Dim birdsList As New List(Of birds)()

    Private Sub bind_grid_with_json()
        Dim sJSON As String
        sJSON = Server.MapPath("birds.json")

        Using sr As New StreamReader(sJSON)
            Dim json As JavaScriptSerializer = New JavaScriptSerializer()

            birdsList = json.Deserialize(Of List(Of birds))(sr.ReadToEnd())

            Dim dt As DataTable = New DataTable()
            With dt
                .Columns.Add("ID", GetType(String))
                .Columns.Add("Name", GetType(String))
                .Columns.Add("Type", GetType(String))
            End With

            For Each val As birds In birdsList
                Dim row As DataRow = dt.NewRow()
                row("ID") = val.ID : row("Name") = val.Name : row("Type") = val.Type

                dt.Rows.Add(row)
            Next

            grd.DataSource = dt
            grd.DataBind()
        End Using
    End Sub

    ' for paging.
    Protected Sub grd_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grd.PageIndexChanging
        grd.PageIndex = e.NewPageIndex
        bind_grid_with_json()
    End Sub
End Class

That's it. Happy coding. 🙂

← PreviousNext →