再谈VB2008中使用JSON

前段时间我在Csdn上发表了一篇文章 VB2008使用.Net3.5扩展方法实现对象JSON序列化

至于如何将数据库的数据序列化成JSON,可以先创建实体类,然后把数据库的数据取出来写进实体类中,再参考上面文章的方法序列化成JSON

下面我演示的是另外一种方法

1、首先要创建一个数据库,上面有一张表,结构如下:

ID int PK,自增
Name varchar(50)  
Email varchar(50)  
Message varchar(50)  
PostDate datetime getdate()

2、下载 ASP.NET Futures

3、创建一个WebApplication

4、添加对C:\Program Files\Microsoft ASP.NET\ASP.NET Futures July 2007\v1.2.61025\3.5\Microsoft.Web.Preview.dll的引用

5、修改Web.config增加以下配置节

  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization>
          <converters>
            <add name="DataSetConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter" />
            <add name="DataRowConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataRowConverter" />
            <add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter" />
          </converters>
        </jsonSerialization>
      </webServices>
    </scripting>
  </system.web.extensions>

这样就能使.Net的数据对象与JSON序列化对应起来了

6、创建一个WebService,用于数据库操作

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Data.SqlClient
Imports System.Web.Script.Services

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://lishewen.com.cn/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class GuestBookService
    Inherits System.Web.Services.WebService

    Dim connstr As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\GuestBook.mdf;Integrated Security=True;User Instance=True"

    '如果想序列化成XML可以把下面一行的注释去掉
    '<ScriptMethod(ResponseFormat:=ResponseFormat.Xml)> _
    <WebMethod()> _
    Public Function GetMessages() As DataTable
        Dim cmdstr = "SELECT * FROM [Message]"
        Dim da As New SqlDataAdapter(cmdstr, connstr)
        Dim dt As New DataTable("Message")
        da.Fill(dt)
        Return dt
    End Function

End Class

上面程序的运行演示:http://webservice.lishewen.com.cn/guestbookservice.asmx

7、创建一个WebForm,测试用AJAX调用WebService

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="ASPXTest.aspx.vb" Inherits="LSWWebService.ASPXTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>

    <script type="text/javascript">
        function btnGetMessages_onclick()
        {
            LSWWebService.GuestBookService.GetMessages(onSucceeded);
        }
        function onSucceeded(result)
        {
            var idColName=result.columns[0].name;
            var nameColName=result.columns[1].name;
            var emailColName=result.columns[2].name;
            var messageColName=result.columns[3].name;
            var postdateColName=result.columns[4].name;
            var rows=result.rows;
            var builder=new Sys.StringBuilder("<table border=1>");
            builder.append(String.format("<tr><th>{0}</th><th>{1}</th><th>{2}</th><th>{3}</th><th>{4}</th></tr>",idColName,nameColName,emailColName,messageColName,postdateColName));
            for(var i=0;i<rows.length;++i)
            {
                builder.append(String.format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>",rows[i][idColName],rows[i][nameColName],rows[i][emailColName],rows[i][messageColName],rows[i][postdateColName]));
            }
            builder.append("</table>");
            $get("result").innerHTML=builder.toString();
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="~/GuestBookService.asmx" />
            </Services>
        </asp:ScriptManager>
        <input id="btnGetMessages" type="button" value="Get Messages" onclick="return btnGetMessages_onclick()" /></div>
    <div id="result">
    </div>
    </form>
</body>
</html>

上面程序的运行演示:http://webservice.lishewen.com.cn/aspxtest.aspx

文章的相关源代码下载:lswwebservice.rar (4.75 kb)

相关讨论请到:http://bbs.lishewen.com.cn/