Create JSON string from the Dataset in C# and VB.Net

In this post I am describing a example by which you can create the JSON string from the datatable object. After creating the JSON from the datatable, You can use it on the client side through the JavaScript.

In the below function named ‘CreateDatatable(), I am creating a the sample datatable.

Private Sub CreateDatatable()
        Dim dt As New DataTable
        For i As Integer = 0 To 10
            dt.Rows(i)(0) = i
            dt.Rows(i)(1) = i & "-Sample"
        Dim _json As String = GetJson(dt)
    End Sub

The following function will return the serialized JSON string. You only need to pass the datatable object in the function as argument.
Before converting the data table to JSON, first we convert the datatable into the List object and than use the JavaScriptSerializer class that provide a method named Serialize that converts an object to a JSON string.

    Private Function GetJson(ByVal dt As DataTable) As String
        Dim Jserializer As New System.Web.Script.Serialization.JavaScriptSerializer()
        Dim rowsList As New List(Of Dictionary(Of String, Object))()
        Dim row As Dictionary(Of String, Object)
        For Each dr As DataRow In dt.Rows
            row = New Dictionary(Of String, Object)()
            For Each col As DataColumn In dt.Columns
                row.Add(col.ColumnName, dr(col))
        Return Jserializer.Serialize(rowsList)
    End Function

If the resulting JSON string exceeds the value of JavaScriptSerializer.MaxJsonLength than InvalidOperationException error exception will be occurs, so take care of this.

The above code will create the JSON string as:


You can set this JSON string to any hidden field or you can get the JSON string from the AJAX method.

One thought on “Create JSON string from the Dataset in C# and VB.Net”

Comments are closed.