Hi nsds,
You are using nested JSON so you need to define Array inside main (Root) class and create one separate class for StudentsCount.
After that read text inside JSON file using File.ReadAllText and DeserializeObject.
Than create DataTable and define Columns, once columns defined Add Rows in DataTable using class properties.
Please refer below sample.
JSON
{
"School": "ABC",
"Location": "yyyyy",
"TotalStaffs": "50",
"StudentsCount": [
{
"ClassA": "80",
"ClassB": "60"
}
]
}
HTML
<asp:GridView ID="gvCustomers" AutoGenerateColumns="true" runat="server">
</asp:GridView>
Namespaces
C#
using System.Data;
using Newtonsoft.Json;
using System.IO;
VB.Net
Imports System.Data
Imports Newtonsoft.Json
Imports System.IO
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
string json = File.ReadAllText(Server.MapPath("~/Data.json"));
Root data = JsonConvert.DeserializeObject<Root>(json);
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("School"),
new DataColumn("Location"),
new DataColumn("TotalStaffs")
});
dt.Columns.Add("ClassA");
dt.Columns.Add("ClassB");
dt.Rows.Add(data.School, data.Location, data.TotalStaffs, data.StudentsCount[0].ClassA, data.StudentsCount[0].ClassB);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
public class StudentsCount
{
public string ClassA { get; set; }
public string ClassB { get; set; }
}
public class Root
{
public string School { get; set; }
public string Location { get; set; }
public string TotalStaffs { get; set; }
public StudentsCount[] StudentsCount { get; set; }
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim json As String = File.ReadAllText(Server.MapPath("~/Data.json"))
Dim data As Root = JsonConvert.DeserializeObject(Of Root)(json)
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn() {New DataColumn("School"), New DataColumn("Location"), New DataColumn("TotalStaffs")})
dt.Columns.Add("ClassA")
dt.Columns.Add("ClassB")
dt.Rows.Add(data.School, data.Location, data.TotalStaffs, data.StudentsCount(0).ClassA, data.StudentsCount(0).ClassB)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Sub
Public Class StudentsCount
Public Property ClassA As String
Public Property ClassB As String
End Class
Public Class Root
Public Property School As String
Public Property Location As String
Public Property TotalStaffs As String
Public Property StudentsCount As StudentsCount()
End Class
Screenshot