8

At the moment, I am building json data as follows:

<%@ Page Language="VB" Debug="True" EnableViewState="false" %>

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">
    Dim objSQLConnection As SqlConnection
    Dim objSQLCommand As SqlCommand
    Dim objSQLDataReader As SqlDataReader
    Dim objJSONStringBuilder As StringBuilder

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Response.Clear()
        Response.ContentType = "application/json"
        Response.Write(get_json())
        Response.End()
    End Sub

    Function get_json() As String
        objJSONStringBuilder = New StringBuilder()
        objSQLConnection = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connString"))

        objSQLCommand = New SqlCommand("sql query goes here", objSQLConnection)

        objJSONStringBuilder.Append("[")

        objSQLCommand.Connection.Open()
        objSQLDataReader = objSQLCommand.ExecuteReader()

        While objSQLDataReader.Read()
            objJSONStringBuilder.Append("{")
            objJSONStringBuilder.Append("""col1""")
            objJSONStringBuilder.Append(":")
            objJSONStringBuilder.Append("""" & objSQLDataReader("col1") & """")
            objJSONStringBuilder.Append(",")
            objJSONStringBuilder.Append("""col2""")
            objJSONStringBuilder.Append(":")
            objJSONStringBuilder.Append("""" & objSQLDataReader("col2") & """")
            objJSONStringBuilder.Append(",")
            objJSONStringBuilder.Append("""col3""")
            objJSONStringBuilder.Append(":")
            objJSONStringBuilder.Append("""" & objSQLDataReader("col3") & """")
            objJSONStringBuilder.Append("},")
        End While

        objSQLDataReader.Close()
        objSQLCommand.Connection.Close()

        objJSONStringBuilder.Remove(objJSONStringBuilder.Length - 1, 1)

        objJSONStringBuilder.Append("]")

        Return objJSONStringBuilder.ToString
    End Function
</script>

Is this the preferred method of creating JSON data using .NET?

I think I am supposed to use asmx web services with arrays converted to json? But all the examples I have seen are in C#.

nami
  • 1,186
  • 5
  • 19
  • 22
  • possible duplicate of [How can I encode an Array in VB.NET to JSON?](http://stackoverflow.com/questions/579053/how-can-i-encode-an-array-in-vb-net-to-json) – Tomalak Jun 23 '11 at 10:47
  • @Tomalak, My question is more geared towards how to create a json web service using asmx files, this I did not see in the link you posted. – nami Jun 23 '11 at 10:51
  • The linked thread has answers how to generate JSON using .NET. I thought that more or less is your question. – Tomalak Jun 23 '11 at 10:53
  • @Tomalak, OK, thanks, but that didn't answer my question, only probably 33% of it was answered with that link. – nami Jun 23 '11 at 10:56
  • @Downvoters, please have enough decency to explain why you have downvoted. – nami Jun 23 '11 at 11:01
  • Also see [System.Runtime.Serialization.Json Namespace](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.aspx) – ToolmakerSteve Dec 03 '14 at 21:21

5 Answers5

9

I don't have VB on my box, but if you want to use JavaScriptSerializer Class your project must target .NET Framework 3.5 or .NET Framework 4.0 (not .NET Framework 3.5 Client Profile neither .NET Framework 4.0 Client Profile). Add System.Web.Extensions.dll to references.

An example in C# is:

public String Index()
{
    Object[] myArray = new Object[3];

    myArray[0] = new { col1 = "foo", col2 = "bar" };
    myArray[1] = new { col1 = "fizz", col2 = "buzz" };
    myArray[2] = new { col1 = "fizz", col2 = "buzz" };

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    return serializer.Serialize(myArray);
}

The output of this function is:

[{"col1":"foo","col2":"bar"},{"col1":"fizz","col2":"buzz"},{"col1":"fizz","col2":"buzz"}]

It should be easy to convert it into VB.

Update: VB version:

Function get_json() As String
    Dim myArray(2) As Object

    myArray(0) = New With {Key .col1 = "foo", .col2 = "bar"}
    myArray(1) = New With {Key .col1 = "fizz", .col2 = "buzz"}
    myArray(2) = New With {Key .col1 = "fizz", .col2 = "buzz"}

    Dim serializer As New JavaScriptSerializer()
    Return serializer.Serialize(myArray)
End Function

Same output, just don´t forget to import System.Web.Script.Serialization.

kiewic
  • 15,852
  • 13
  • 78
  • 101
8

Normally, with ASP.NET, you shouldn't be doing anything to serialize to JSON. Just make your request with the correct type, return it correctly, and ASP.NET will serialize to JSON for you. It can also deserialize.

Peter
  • 13,733
  • 11
  • 75
  • 122
2

You can try Json.NET. It's a very popular library for handle json object on .net platform.

ADIMO
  • 1,107
  • 12
  • 24
0

JavaScriptSerializer Class

The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.

To serialize an object, use the Serialize method. To deserialize a JSON string, use the Deserialize or DeserializeObject methods. To serialize and deserialize types that are not natively supported by JavaScriptSerializer, implement custom converters by using the JavaScriptConverter class. Then register the converters by using the RegisterConverters method.

vtortola
  • 34,709
  • 29
  • 161
  • 263
  • based on Tomalak commend, I understand that I can use that class to convert arrays to json. How do I convert my existing code to an array before that array can be used in that class? – nami Jun 23 '11 at 10:58
  • Sorry, I don't understand your question, can you rephrase it? – vtortola Jun 23 '11 at 11:01
  • based on Tomalak comment, I understand that I can use that class to convert arrays to json. How do I convert my existing code to an array before that array can be used in that class? – nami Jun 23 '11 at 11:15
  • rephrase means "express in an alternative way" :P – vtortola Jun 23 '11 at 11:18
  • before I can use the JavaScriptSerializer class, I need to convert my stringbuilder to an array, which I do not know how to do. – nami Jun 23 '11 at 11:27
0

Have you tried DataContractJsonSerializer ? http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx

ZFE
  • 301
  • 2
  • 8