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
        dt.Columns.Add("id")
        dt.Columns.Add("name")
        For i As Integer = 0 To 10
            dt.Rows.Add()
            dt.Rows(i)(0) = i
            dt.Rows(i)(1) = i & "-Sample"
        Next
        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))
            Next
            rowsList.Add(row)
        Next
        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:

[{"id":"0","name":"0-Sample"},{"id":"1","name":"1-Sample"},{"id":"2","name":"2-Sample"},{"id":"3","name":"3-Sample"},{"id":"4","name":"4-Sample"},{"id":"5","name":"5-Sample"},{"id":"6","name":"6-Sample"},{"id":"7","name":"7-Sample"},{"id":"8","name":"8-Sample"},{"id":"9","name":"9-Sample"},{"id":"10","name":"10-Sample"}]

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.