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#.
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.