I searched high and wide for something simple to do this and every function I found basically reinvented the wheel from scratch. If you do any amount of searching, you can find the
object which will convert objects to JSON. Sounds easy enough...WRONG! Even converting an empty
will return a circular reference exception.
On a similar note, I found several articles claiming to convert XML to JSON using the same function. The "solution" was something like this:
Dim jsonString As String = jss.Serialize(DataSet1.GetXML())
I tried this thinking it made sense. But instead of serializing the data in the XML, it simply dumps the entire XML
into a single element in the JSON
. I'm pretty sure that's not what anyone wants it to do.
So how do you do it? Well, there are a number of methods, but I found the quickest and easiest is to just convert your
object, then use the
to make the conversion.
Here's the code:
Function DataSetToJSON(ds As DataSet) As String
Dim dict As New Dictionary(Of String, Object)
For Each dt As DataTable In ds.Tables
Dim arr(dt.Rows.Count) As Object
For i As Integer = 0 To dt.Rows.Count - 1
arr(i) = dt.Rows(i).ItemArray
If you're looking to convert XML to JSON and write the least amount of code, you can just write it to a
on the fly like this:
I know it sounds crazy, but both of these methods are really simple and execute really fast. And you don't need to know about XLT or anything else. Oh, and the only libraries you need are
When it comes around to referencing the JSON object from your browser, you can access the elements like so:
If anyone knows how to make the conversion, you can reference it by
, I would love to see it.