本文為機器翻譯文章。如需檢視英文版,請選取 [原文] 核取方塊。您也可以將滑鼠指標移到文字上,即可在快顯視窗顯示英文原文。
譯文
原文

JavaScriptSerializer 類別

 

Json.NET,用於序列化和還原序列化。 為具有 AJAX 能力的應用程式提供序列化和還原序列化功能。

命名空間:   System.Web.Script.Serialization
組件:  System.Web.Extensions (於 System.Web.Extensions.dll)

System.Object
  System.Web.Script.Serialization.JavaScriptSerializer

public class JavaScriptSerializer

名稱描述
System_CAPS_pubmethodJavaScriptSerializer()

初始化 JavaScriptSerializer 類別的新執行個體,該執行個體沒有類型解析程式。

System_CAPS_pubmethodJavaScriptSerializer(JavaScriptTypeResolver)

初始化 JavaScriptSerializer 類別的新執行個體,該執行個體有自訂的類型解析程式。

名稱描述
System_CAPS_pubpropertyMaxJsonLength

取得或設定 JavaScriptSerializer 類別接受的 JSON 字串最大長度。

System_CAPS_pubpropertyRecursionLimit

取得或設定要處理物件層級數目的限制。

名稱描述
System_CAPS_pubmethodConvertToType(Object, Type)

將指定的物件轉換成指定的類型。

System_CAPS_pubmethodConvertToType<T>(Object)

將指定的物件轉換為指定類型。

System_CAPS_pubmethodDeserialize(String, Type)

將 JSON 格式化字串轉換成指定之類型的物件。

System_CAPS_pubmethodDeserialize<T>(String)

將指定的 JSON 字串轉換成 T 類型的物件。

System_CAPS_pubmethodDeserializeObject(String)

將指定的 JSON 字串轉換成物件圖形。

System_CAPS_pubmethodEquals(Object)

判斷指定的物件是否等於目前的物件。(繼承自 Object。)

System_CAPS_protmethodFinalize()

在記憶體回收開始前,允許物件嘗試釋放資源,並執行其他清除作業。(繼承自 Object。)

System_CAPS_pubmethodGetHashCode()

做為預設雜湊函式。(繼承自 Object。)

System_CAPS_pubmethodGetType()

取得目前執行個體的 Type(繼承自 Object。)

System_CAPS_protmethodMemberwiseClone()

建立目前 Object 的淺層複製。(繼承自 Object。)

System_CAPS_pubmethodRegisterConverters(IEnumerable<JavaScriptConverter>)

JavaScriptSerializer 執行個體註冊自訂轉換子。

System_CAPS_pubmethodSerialize(Object)

將物件轉換成 JSON 字串。

System_CAPS_pubmethodSerialize(Object, StringBuilder)

序列化物件並將產生的 JSON 字串寫入指定的 StringBuilder 物件中。

System_CAPS_pubmethodToString()

傳回代表目前物件的字串。(繼承自 Object。)

The T:System.Web.Script.Serialization.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 Overload:System.Web.Script.Serialization.JavaScriptSerializer.Serialize method. To deserialize a JSON string, use the M:System.Web.Script.Serialization.JavaScriptSerializer.Deserialize``1(System.String) or M:System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(System.String) methods. To serialize and deserialize types that are not natively supported by T:System.Web.Script.Serialization.JavaScriptSerializer, implement custom converters by using the T:System.Web.Script.Serialization.JavaScriptConverter class. Then register the converters by using the M:System.Web.Script.Serialization.JavaScriptSerializer.RegisterConverters(System.Collections.Generic.IEnumerable{System.Web.Script.Serialization.JavaScriptConverter}) method.

The following table shows the mapping between managed types and JSON for the serialization process. These managed types are natively supported by T:System.Web.Script.Serialization.JavaScriptSerializer. When you are deserializing from a JSON string to a managed type, the same mapping applies. However, deserialization can be asymmetric; not all serializable managed types can be deserialized from JSON.

System_CAPS_note注意

A multidimensional array is serialized as a one-dimensional array, and you should use it as a flat array.

Managed type

JSON equivalent

String (UTF-8 encoding only).

String

Char

String

Single null char (such as, \0 )

Null

Boolean

Boolean. Represented in JSON as true or false

null (null object references and Nullable value types).

A string value of null

DBNull

A string value of null

Primitive numeric (or numeric-compatible) types: T:System.Byte, T:System.SByte, T:System.Int16, T:System.Int32, T:System.Int64, T:System.UInt16, T:System.UInt32, T:System.UInt64, T:System.Double, and T:System.Single. The culture-invariant string representation is used.

Number

DateTime

Date object, represented in JSON as "\/Date(number of ticks)\/". The number of ticks is a positive or negative long value that indicates the number of ticks (milliseconds) that have elapsed since midnight 01 January, 1970 UTC.

The maximum supported date value is F:System.DateTime.MaxValue (12/31/9999 11:59:59 PM) and the minimum supported date value is F:System.DateTime.MinValue (1/1/0001 12:00:00 AM).

Enumerations of integer type

Integer equivalent of the enumeration value

Types that implement T:System.Collections.IEnumerable or T:System.Collections.Generic.IEnumerable`1 that are not also implementations of T:System.Collections.IDictionary or T:System.Collections.Generic.IDictionary`2. This includes types such as T:System.Array, T:System.Collections.ArrayList, and T:System.Collections.Generic.List`1.

Array that uses JSON array syntax

Types that implement T:System.Collections.IDictionary or T:System.Collections.Generic.IDictionary`2. This includes types such as T:System.Collections.Generic.Dictionary`2 and T:System.Collections.Hashtable.

JavaScript object that uses JSON dictionary syntax

Custom concrete (non-abstract) types that have public instance properties that have get accessors or public instance fields.

Note that public write-only properties, public property or public field attributes marked with T:System.Web.Script.Serialization.ScriptIgnoreAttribute, and public indexed properties in these types are ignored.

JavaScript object that uses JSON dictionary syntax. A special metadata property named "__type" is included to ensure correct deserialization. Make sure that public instance properties have get and set accessors to ensure correct deserialization.

Guid

String representation of a GUID

Uri

String representation of the return value of M:System.Uri.GetComponents(System.UriComponents,System.UriFormat)

The first example provides a simple illustration of how to serialize and deserialize data objects. It requires a class names Person which is shown below.

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.Script.Serialization;

namespace ExampleApplication
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var RegisteredUsers = new List<Person>();
            RegisteredUsers.Add(new Person() { PersonID = 1, Name = "Bryon Hetrick", Registered = true });
            RegisteredUsers.Add(new Person() { PersonID = 2, Name = "Nicole Wilcox", Registered = true });
            RegisteredUsers.Add(new Person() { PersonID = 3, Name = "Adrian Martinson", Registered = false });
            RegisteredUsers.Add(new Person() { PersonID = 4, Name = "Nora Osborn", Registered = false });

            var serializer = new JavaScriptSerializer();
            var serializedResult = serializer.Serialize(RegisteredUsers);
            // Produces string value of:
            // [
            //     {"PersonID":1,"Name":"Bryon Hetrick","Registered":true},
            //     {"PersonID":2,"Name":"Nicole Wilcox","Registered":true},
            //     {"PersonID":3,"Name":"Adrian Martinson","Registered":false},
            //     {"PersonID":4,"Name":"Nora Osborn","Registered":false}
            // ]

            var deserializedResult = serializer.Deserialize<List<Person>>(serializedResult);
            // Produces List with 4 Person objects
        }
    }
}
using System;

namespace ExampleApplication
{
    public class Person
    {
        public int PersonID { get; set; }
        public string Name { get; set; }
        public bool Registered { get; set; }
    }
}

The next example shows a more complicated and complete project that uses the T:System.Web.Script.Serialization.JavaScriptSerializer class to save and restore the state of an object by using JSON serialization. This code uses a custom converter that is provided for the T:System.Web.Script.Serialization.JavaScriptConverter class.

<%@ Page Language="C#" %>
<%@ 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">

    JavaScriptSerializer serializer;
    protected void Page_Load(object sender, EventArgs e)
    {
        serializer = new JavaScriptSerializer();

        // Register the custom converter.
        serializer.RegisterConverters(new JavaScriptConverter[] { 
            new System.Web.Script.Serialization.CS.ListItemCollectionConverter() });
        this.SetFocus(TextBox1);
    }

    protected void saveButton_Click(object sender, EventArgs e)
    {
        // Save the current state of the ListBox control.
        SavedState.Text = serializer.Serialize(ListBox1.Items);
        recoverButton.Enabled = true;
        Message.Text = "State saved";
    }

    protected void recoverButton_Click(object sender, EventArgs e)
    {        
        //Recover the saved items of the ListBox control.
        ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection>(SavedState.Text);
        ListItem[] newListItemArray = new ListItem[recoveredList.Count];
        recoveredList.CopyTo(newListItemArray, 0);
        ListBox1.Items.Clear();
        ListBox1.Items.AddRange(newListItemArray);
        Message.Text = "Last saved state recovered.";
    }

    protected void clearButton_Click(object sender, EventArgs e)
    {
        // Remove all items from the ListBox control.
        ListBox1.Items.Clear();
        Message.Text = "All items removed";
    }

    protected void ContactsGrid_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Get the currently selected row using the SelectedRow property.
        GridViewRow row = ContactsGrid.SelectedRow;

        // Get the ID of item selected.
        string itemId = ContactsGrid.DataKeys[row.RowIndex].Value.ToString();                
        ListItem newItem = new ListItem(row.Cells[4].Text, itemId);

        // Check if the item already exists in the ListBox control.
        if (!ListBox1.Items.Contains(newItem))
        {
            // Add the item to the ListBox control.
            ListBox1.Items.Add(newItem);
            Message.Text = "Item added";
        }
        else
            Message.Text = "Item already exists";
    }

    protected void ContactsGrid_PageIndexChanged(object sender, EventArgs e)
    {
        //Reset the selected index.
        ContactsGrid.SelectedIndex = -1;
    }

    protected void searchButton_Click(object sender, EventArgs e)
    {
        //Reset indexes.
        ContactsGrid.SelectedIndex = -1;
        ContactsGrid.PageIndex = 0;

        //Set focus on the TextBox control.
        ScriptManager1.SetFocus(TextBox1);
    }

    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        // Show/hide the saved state string.        
        SavedState.Visible = CheckBox1.Checked;
        StateLabel.Visible = CheckBox1.Checked;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<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>

.NET Framework
自 3.5 起供應

此類型的任何 public static (在 Visual Basic 中 共用 在 Visual Basic 中) 成員皆為安全執行緒。不保證任何執行個體成員為安全執行緒。

System.Web.Script.Serialization 命名空間
Using Web Services in ASP.NET AJAX
Calling Web Services from Client Script in ASP.NET AJAX

回到頁首
顯示: