Monthly Archives: February 2011

Converting DataSet to JSon

When you can create RESTful webservices using WCF and send response in JSon format. Mostly we faced issues converting Dataset/Datatable to JSon string, the following code is simple and most of them may know about this but just for those who are in a hurry . This is written in VB, mostly you find some help for C# but not for VB and also note this works well with .Net 3.5/4.0

You can create your own (custom) dataset

Public Class MyDataSet
	Inherits System.Data.DataSet

	Public Sub New()
	End Sub

	Public Function toJSon() As String
		Dim response As String = “”
			If (Me.Tables.Count > 0) Then
				Dim serialize As JavaScriptSerializer = New JavaScriptSerializer()
				response = serialize.Serialize(ToDictionary(Me))
			End If
		Catch ex As Exception
		End Try
		Return response
	End Function

	Private Function toTableDictionary(ByVal data As DataTable) As Object
		Dim dic As Dictionary(Of String, Object) = New Dictionary(Of String, Object)
		dic.Add(data.TableName, toRowDictionary(data))
		Return dic
	End Function

	Private Function toRowDictionary(ByVal data As DataTable) As Object
		Dim col = data.Columns.Cast(Of DataColumn)().ToArray
		Return data.Rows.Cast(Of DataRow)().Select(Function(r)col.ToDictionary(Function(c) c.ColumnName, Function(c) r(c)))
	End Function

	Private Function ToDictionary(ByVal data As DataSet) As Dictionary(Of String, Object)
		Return data.Tables.Cast(Of DataTable)().ToDictionary(Function(t)t.TableName, Function(t) toRowDictionary(t))
	End Function

End Class

you can use this dataset and call the .toJson just as you call .toString()

Hope this helps someone in need…