Wednesday, July 21, 2010

JSON Conversions

So, I am integrating a provided web page into a Manage 2000 site and I need to supply this external page with a JSON array of data on the querystring based on the contents of a Manage 2000 TM Table.

How to get a JSON serialization out to the client world?

There is a very nice little namespace that I have not previously run across, System.Web.Script.Serialization. And in it you will find a JavaScriptSerializer class (read JSON serializer!).

With the JavaScriptSerializer you can convert a .Net Hash to or from a JSON object, or a .Net System.Array to or from a JSON array, or a bunch of other mappings including your own.

In my case I want to end up with a JSON array of elements with each element comprised of an array of code description pairs.

Private Function GetTMTableAsJSONArray(ByVal TableNbr As String) As System.Text.StringBuilder
Dim result As New System.Text.StringBuilder
Dim TM As New System.Collections.Generic.List(Of Array)
Dim ds As New ROISystems.Components.roiDataSet
ds = TableMaster.GetTable(TableNbr)
For Each entry As DataRow In ds.Tables("VALIDATION_Validation_Info").Rows
Dim row() As String = {"", ""}
row(0) = entry.Item("Code")
row(1) = entry.Item("Desc")
TM.Add(row)
Next
Dim JSONSerializer As New System.Web.Script.Serialization.JavaScriptSerializer
result.Append(JSONSerializer.Serialize(TM))
Return result

End Function

Yes, the JavaScriptSerializer is my new favorite toy for transforming data during client side AJAX activity.

No comments: