JavaScriptSerializer 类 Home
This page is specific to:.NET Framework Version:3.5
.NET Framework 类库
JavaScriptSerializer 类

更新:2007 年 11 月

为启用 AFAX 的应用程序提供序列化和反序列化功能。

命名空间:  System.Web.Script.Serialization
程序集:  System.Web.Extensions(在 System.Web.Extensions.dll 中)

语法

<AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
Public Class JavaScriptSerializer
Dim instance As JavaScriptSerializer
我们尚未提供此语言的代码示例。
/** @attribute AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal) */
/** @attribute AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal) */
public class JavaScriptSerializer
备注

JavaScriptSerializer 类由异步通信层内部使用,用于序列化和反序列化在浏览器和 Web 服务器之间传递的数据。您无法访问序列化程序的此实例。但是,此类公开了公共 API。因此,当您希望在托管代码中使用 JavaScript 对象符号 (JSON) 时可以使用此类。

若要序列化对象,请使用 Serialize 方法。若要反序列化 JSON 字符串,请使用 Deserialize<(Of <(T>)>)DeserializeObject 方法。若要序列化和反序列化 JavaScriptSerializer 本身不支持的类型,请使用 JavaScriptConverter 类来实现自定义转换器。然后,使用 RegisterConverters 方法注册转换器。

托管类型和 JSON 之间的映射

下表显示序列化进程中托管类型和 JSON 之间的映射。JavaScriptSerializer 本身支持这些托管类型。将 JSON 字符串反序列化为托管类型时,采用相同的映射。但是,反序列化可能是非对称的,并非所有可序列化的托管类型都可以从 JSON 反序列化得到。

说明:

多维数组将序列化为一维数组,您应该将其用作平面数组。

托管类型

JSON 等效项

String(仅限 UTF-8 编码)。

String

Char

String

单个 null 字符(如,\0)

Null

Boolean

Boolean。在 JSON 中表示为 truefalse

nullNothingnullptrnull 引用(在 Visual Basic 中为 NothingnullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing 对象引用和 Nullable 值类型)。

一个空的字符串值

DBNull

一个空的字符串值

基元数值(或兼容数值)类型包括:ByteSByteInt16Int32Int64UInt16UInt32UInt64DoubleSingle。使用区域性固定的字符串表示形式。

数字

DateTime

Date 对象,在 JSON 中表示为“\/Date(刻度数)\/”。刻度数是一个正的或负的长值,该值指示从 UTC 1970 年 1 月 1 日午夜开始已经过的刻度数(毫秒)。

所支持的最大日期值为 MaxValue(9999 年 12 月 31 日 11:59:59 PM),而所支持的最小日期值为 MinValue(0001 年 1 月 1 日 12:00:00 AM)。

整数类型的枚举

枚举值的整数等效项

实现 IEnumerableSystem.Collections.Generic..::.IEnumerable<(Of <(T>)>) 的类型,但同时它们并非 IDictionarySystem.Collections.Generic..::.IDictionary<(Of <(TKey, TValue>)>) 的实现。这包括多种类型,如 ArrayArrayListList<(Of <(T>)>)

使用 JSON 数组语法的数组

实现 IDictionarySystem.Collections.Generic..::.IDictionary<(Of <(TKey, TValue>)>) 的类型。这包括多种类型,如 Dictionary<(Of <(TKey, TValue>)>)Hashtable

使用 JSON 字典语法的 JavaScript 对象

具有公共实例属性的自定义具体(非抽象)类型,这些属性具有 get 访问器或公共实例字段。

请注意,公共只写属性 (Property)、使用 ScriptIgnoreAttribute 标记的公共属性 (Property) 或公共字段属性 (Attribute) 以及这些类型的公共索引属性 (Property) 都将被忽略。

使用 JSON 字典语法的 JavaScript 对象。还包括一个名为“__type”的特定元数据属性,用于确保反序列化正确执行。请确保公共实例属性包含 get 访问器和 set 访问器以确保反序列化正确执行。

Guid

GUID 的字符串表示形式

Uri

GetComponents 的返回值的字符串表示形式

示例

下面的示例演示如何通过使用 JSON 序列化来使用 JavaScriptSerializer 类保存和还原对象的状态。此代码使用为 JavaScriptConverter 类提供的自定义转换器。

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Dim serializer As JavaScriptSerializer

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        serializer = New JavaScriptSerializer()

        ' Register the custom converter.
        serializer.RegisterConverters(New JavaScriptConverter() _
            {New System.Web.Script.Serialization.VB.ListItemCollectionConverter()})
    End Sub

    Protected Sub saveButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Save the current state of the ListBox control.
        SavedState.Text = serializer.Serialize(ListBox1.Items)
        recoverButton.Enabled = True
        Message.Text = "State saved"
    End Sub

    Protected Sub recoverButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Recover the saved items of the ListBox control.        
        Dim recoveredList As ListItemCollection = _
            serializer.Deserialize(Of ListItemCollection)(SavedState.Text)
        Dim newListItemArray(recoveredList.Count - 1) As ListItem
        recoveredList.CopyTo(newListItemArray, 0)
        ListBox1.Items.Clear()
        ListBox1.Items.AddRange(newListItemArray)
        Message.Text = "Last saved state recovered."
    End Sub

    Protected Sub clearButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Remove all items from the ListBox control.
        ListBox1.Items.Clear()
        Message.Text = "All items removed"
    End Sub

    Protected Sub ContactsGrid_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        ' Get the currently selected row using the SelectedRow property.
        Dim row As GridViewRow = ContactsGrid.SelectedRow

        ' Get the ID of the item selected.
        Dim itemId As String = ContactsGrid.DataKeys(row.RowIndex).Value.ToString()
        Dim newItem As ListItem = New ListItem(row.Cells(4).Text, itemId)

        ' Check if the item already exists in the ListBox control.
        If Not ListBox1.Items.Contains(newItem) Then
            ' Add the item to the ListBox control.
            ListBox1.Items.Add(newItem)
            Message.Text = "Item added"
        Else
            Message.Text = "Item already exists"
        End If

    End Sub

    Private Function SearchItem(ByVal itemId As String) As Boolean
        Dim i As Integer
        For i = 0 To ListBox1.Items.Count - 1
            If ListBox1.Items(i).Value = itemId Then
                Return True
            End If
        Next i
        Return False

    End Function

    Protected Sub ContactsGrid_PageIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        ContactsGrid.SelectedIndex = -1
    End Sub

    Protected Sub searchButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        ContactsGrid.SelectedIndex = -1
        ContactsGrid.PageIndex = 0
        ScriptManager1.SetFocus(TextBox1)
    End Sub

    Protected Sub CheckBox1_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
        SavedState.Visible = CheckBox1.Checked
        StateLabel.Visible = CheckBox1.Checked
    End Sub
</script>

<html  >
<head runat="server">
    <title>Save/Recover state</title>
    <style type="text/css">
        body {  font: 11pt Trebuchet MS;
                font-color: #000000;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    </style>
</head>
<body>    
    <form id="form1" runat="server" defaultbutton="searchButton" defaultfocus="TextBox1">
        <h3>
            <span style="text-decoration: underline">
                                    Contacts Selection</span><br />
        </h3>
        <asp:ScriptManager runat="server" ID="ScriptManager1" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                Type contact's first name:
                <asp:TextBox ID="TextBox1" runat="server" />
                <asp:Button ID="searchButton" runat="server" Text="Search" OnClick="searchButton_Click" />&nbsp;
                <br />
                <br />
                <table border="0" width="100%">
                    <tr>
                        <td style="width:50%" valign="top" align="center">
                            <b>Search results:</b><br />
                            <asp:GridView ID="ContactsGrid" runat="server" AutoGenerateColumns="False"
                                CellPadding="4" DataKeyNames="ContactID" DataSourceID="SqlDataSource1"
                                OnSelectedIndexChanged="ContactsGrid_SelectedIndexChanged" ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="7" OnPageIndexChanged="ContactsGrid_PageIndexChanged">
                                <Columns>
                                    <asp:CommandField ShowSelectButton="True" ButtonType="Button" />
                                    <asp:BoundField DataField="ContactID" HeaderText="ContactID" SortExpression="ContactID" Visible="False" />
                                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
                                    <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
                                    <asp:BoundField DataField="EmailAddress" HeaderText="EmailAddress" SortExpression="EmailAddress" />
                                </Columns>
                                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                                <EditRowStyle BackColor="#999999" />
                                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                                <EmptyDataTemplate>No data found.</EmptyDataTemplate>
                            </asp:GridView>
                            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
                                SelectCommand="SELECT ContactID, FirstName, LastName, EmailAddress FROM Person.Contact WHERE (UPPER(FirstName) = UPPER(@FIRSTNAME))" >
                                <SelectParameters>
                                    <asp:ControlParameter Name="FIRSTNAME" ControlId="TextBox1" Type="String" />
                                </SelectParameters>
                            </asp:SqlDataSource>
                        </td>
                        <td valign="top">
                            <b>Contacts list:</b><br />
                        <asp:ListBox ID="ListBox1" runat="server" Height="200px" Width="214px" /><br />
                        <asp:Button ID="saveButton" runat="server" Text="Save state" OnClick="saveButton_Click" ToolTip="Save the current state of the list" />
                        <asp:Button ID="recoverButton" runat="server" Text="Recover saved state" OnClick="recoverButton_Click" Enabled="false" ToolTip="Recover the last saved state" />
                        <asp:Button ID="clearButton" runat="server" Text="Clear" OnClick="clearButton_Click" ToolTip="Remove all items from the list" /><br />
                            <br />
                            <asp:CheckBox ID="CheckBox1" runat="server" Checked="True" OnCheckedChanged="CheckBox1_CheckedChanged"
                                Text="Show saved state" AutoPostBack="True" /></td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <br />
                            <br />
                            &nbsp;&nbsp;
                            <hr />
                            Message: <asp:Label ID="Message" runat="server" ForeColor="SteelBlue" />&nbsp;&nbsp;<br />
                            <asp:Label ID="StateLabel" runat="server" Text="State:"></asp:Label>
                            <asp:Label ID="SavedState" runat="server"/><br />                        
                        </td>
                    </tr>
                </table>
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:UpdateProgress ID="UpdateProgress1" runat="server">
            <ProgressTemplate>
                <asp:Image ID="Image1" runat="server" ImageUrl="..\images\spinner.gif" />&nbsp;Processing...
            </ProgressTemplate>
        </asp:UpdateProgress>
    </form>
</body>
</html>


权限

继承层次结构

System..::.Object
  System.Web.Script.Serialization..::.JavaScriptSerializer
线程安全

此类型的任何公共 static(在 Visual Basic 中为 Shared) 成员都是线程安全的。但不保证所有实例成员都是线程安全的。
平台

Windows Vista, Windows XP SP2, Windows Server 2003

.NET Framework 和 .NET Compact Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求

版本信息

.NET Framework

受以下版本支持:3.5
另请参见

参考

其他资源

© 2009 Microsoft Corporation 版权所有。   保留所有权利 | 商标 | 隐私权声明
Page view tracker
为轻量型库评级
x
依无脚本原则生成的轻量型库 (loband),添加了大家要求的功能:搜索框和默认代码语言选择。
您喜欢这个搜索框吗?
您喜欢标签式代码块吗?
此主题有用吗?
提供详细反馈。
谢谢
x
感谢您帮助改善 MSDN Online。
反馈意见
切换视图
经典视图
轻量型视图
无脚本视图
切换视图