Jun
26
2009

Konversi dataset ke JSON

Kode berikut berguna untuk mengkonversi dataset ke format JSON, untuk gampangnya, serialisasi ke JSON menggunakan library JSON.NET, di websitenya ada beberapa versi tergantung versi .net framework yang digunakan. BTW, ini kodenya :

Imports Newtonsoft.Json

	Private Function GetCustomer() As String

		Dim retVal As String = ""
		Dim ds As DataSet = DAL.Customer.GetCustomers

		If ds IsNot Nothing AndAlso ds.Tables(0).Rows.Count > 0 Then

		Dim custList As New List(Of Hashtable)()

		For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
			 Dim ht As New Hashtable()
			 Dim row As DataRow = TryCast(ds.Tables(0).Rows(i), DataRow)
			 ht("IDCustomer") = Convert.ToString(row("IDCustomer"))
			 ht("CustomerName") = Convert.ToString(row("CustomerName"))
			 custList.Add(ht)
		Next

		retVal = JavaScriptConvert.SerializeObject(custList)

		End If

		Return retVal

End Function

Output yang dihasilkan adalah sebagai berikut (setelah dirapikan):

[
{"IDCustomer":"1","CustomerName":"Unyil"},
{"IDCustomer":"2","CustomerName":"Cuplis"},
{"IDCustomer":"3","CustomerName":"Ableh"}
]

Related Posts

About the Author: Danni Afasyah

7 Comments + Add Comment

  • maaf nu bee, implementasi buat apa mas Danni

  • misalnya kepake buat ngisi data gridnya extjs dari asp.net :)

  • mas mau tanya…
    DAL apanya y?
    apakah class?

    maaf kalau pertanyaannya kurang berbobot…

  • yup, itu classs yang handle koneksi ke database (DAL -> Data Access Layer).

  • Mas mau tanya,
    misal webservisnya pake format json, terus mau di tampilin hasilnya di VB.net
    gmna ya caranya?? thx ya bantuaannya

  • Klo di balik gimana caranya? (JSON > Dataset)
    Apa perlu di deserialize?
    Makasih makasih ^^

  • pake ini aja gan .. http://james.newtonking.com/pages/json-net.aspx lebih komplit :D

Leave a comment