Convert JSON string to DataTable in ASP.Net using VB.NET


In this article, I’m going to demonstrate with an example, how to convert a JSON string to a DataTable in ASP.NET using VB.NET. for the sake of this articles, I’m gonna create a static JSON file and use IO class to read from it. You can, however, have the JSON string created from a database, WEB API call, etc…   At the end of this article, I will bind the Converted data to a GridView so you can see the result.

Now let’s get started by creating the JSON file Data.json

[
   {
    
      "Name":"Scott",
      "Department":"Information Technology"
   },
   {

      "Name":"Martha",
      "Department":"Engineering"
   },
   {

      "Name":"Maria",
      "Department":"Human Resource"
   },
   {

      "Name":"James",
      "Department":"Information Technology"
   }
]

Now add a DataGrid to your ASPX file to bind the datatable to it.

<div> <asp:GridView  CssClass="dg" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" ID="gv" runat="server">
</asp:GridView></div>

Now add the CSS below in the Header section of your page.

    <style>
        .dg {
            border: solid 1px black;
        }

        .header {
            font-family: Arial;
            color: white;
            background-color: darkorchid;
            border: medium 0px transparent;
            height: 30px;
            text-align: center;
            font-size: 16px;
        }

        .rows {
            background-color: #fff;
            font-family: Arial;
            font-size: 14px;
            color: #000;
            min-height: 25px;
            text-align: left;
            border: medium 0px transparent;
        }

        .dg td {
            padding: 5px;
        }

        .dg th {
            padding: 5px;
        }
    </style>

Now, add the code below to the page load event.

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        If Not Me.IsPostBack Then
            Dim json As String = IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/Data.json"))
            Dim dt As New System.Data.DataTable
            dt = Newtonsoft.Json.JsonConvert.DeserializeObject(Of DataTable)(json)
            gv.DataSource = dt
            gv.DataBind()
        End If

    End Sub

Run the application

The result

Related Articles

Asha Shoukeir

About Asha shoukeir

Software Developer and System Administrator

View all posts by Asha shoukeir →

Leave a Reply