JavaScriptSerializer JavaScriptSerializer JavaScriptSerializer JavaScriptSerializer Class

定義

Json.NET 應該用於序列化和還原序列化。Json.NET should be used for serialization and deserialization. 為具有 AJAX 能力的應用程式提供序列化和還原序列化功能。Provides serialization and deserialization functionality for AJAX-enabled applications.

public ref class JavaScriptSerializer
public class JavaScriptSerializer
type JavaScriptSerializer = class
Public Class JavaScriptSerializer
繼承
JavaScriptSerializerJavaScriptSerializerJavaScriptSerializerJavaScriptSerializer

範例

第一個範例提供如何序列化和還原序列化資料物件的簡單圖解。The first example provides a simple illustration of how to serialize and deserialize data objects. 它需要一個名為 Person 的類別, 如下所示。It requires a class named 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
        }
    }
}
Imports System.Web.Script.Serialization

Public Class _Default
    Inherits Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Dim RegisteredUsers As New List(Of Person)()
        RegisteredUsers.Add(New Person With {.PersonID = 1, .Name = "Bryon Hetrick", .Registered = True})
        RegisteredUsers.Add(New Person With {.PersonID = 2, .Name = "Nicole Wilcox", .Registered = True})
        RegisteredUsers.Add(New Person With {.PersonID = 3, .Name = "Adrian Martinson", .Registered = False})
        RegisteredUsers.Add(New Person With {.PersonID = 4, .Name = "Nora Osborn", .Registered = False})

        Dim serializer As New JavaScriptSerializer()
        Dim 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}
        ' ]

        Dim deserializedResult = serializer.Deserialize(Of List(Of Person))(serializedResult)
        ' Produces List with 4 Person objects
    End Sub
End Class
namespace ExampleApplication
{
    public class Person
    {
        public int PersonID { get; set; }
        public string Name { get; set; }
        public bool Registered { get; set; }
    }
}
Public Class Person
    Public Property PersonID As Integer
    Public Property Name As String
    Public Property Registered As Boolean
End Class

下一個範例顯示更複雜且完整的專案, 其使用JavaScriptSerializer類別來儲存和還原物件的狀態, 方法是使用 JSON 序列化。The next example shows a more complicated and complete project that uses the JavaScriptSerializer class to save and restore the state of an object by using JSON serialization. 這段程式碼會使用針對JavaScriptConverter類別提供的自訂轉換器。This code uses a custom converter that is provided for the 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)
    {
        //<Snippet1>
        serializer = new JavaScriptSerializer();
        
        // Register the custom converter.
        serializer.RegisterConverters(new JavaScriptConverter[] { 
            new System.Web.Script.Serialization.CS.ListItemCollectionConverter() });
        //</Snippet1>
        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>
<%@ 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)
        '<Snippet1>
        serializer = New JavaScriptSerializer()
    
        ' Register the custom converter.
        serializer.RegisterConverters(New JavaScriptConverter() _
            {New System.Web.Script.Serialization.VB.ListItemCollectionConverter()})
        '</Snippet1>
    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 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>

備註

非同步通訊層會在內部使用類別,將瀏覽器與Web服務器之間傳遞的資料序列化和還原序列化。JavaScriptSerializerThe 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. 不過, 此類別會公開公用 API。However, this class exposes a public API. 因此, 當您想要使用 managed 程式碼中的 JavaScript 物件標記法 (JSON) 時, 可以使用類別。Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.

若要序列化物件, 請使用Serialize方法。To serialize an object, use the Serialize method. 若要將 JSON 字串還原序列化, DeserializeDeserializeObject使用或方法。To deserialize a JSON string, use the Deserialize or DeserializeObject methods. 若要序列化和還原序列化原本不支援JavaScriptSerializer的類型, 請JavaScriptConverter使用類別來執行自訂轉換器。To serialize and deserialize types that are not natively supported by JavaScriptSerializer, implement custom converters by using the JavaScriptConverter class. 然後使用RegisterConverters方法註冊轉換器。Then register the converters by using the RegisterConverters method.

Managed 類型與 JSON 之間的對應Mapping Between Managed Types and JSON

下表顯示序列化程式的 managed 類型與 JSON 之間的對應。The following table shows the mapping between managed types and JSON for the serialization process. 這些 managed 類型原本就受到的JavaScriptSerializer支援。These managed types are natively supported by JavaScriptSerializer. 當您從 JSON 字串還原序列化為 managed 類型時, 會套用相同的對應。When you are deserializing from a JSON string to a managed type, the same mapping applies. 不過, 還原序列化可以是非對稱的;並非所有可序列化的 managed 類型都可以從 JSON 還原序列化。However, deserialization can be asymmetric; not all serializable managed types can be deserialized from JSON.

注意

多維陣列會序列化為一維陣列, 您應該使用它做為一般陣列。A multidimensional array is serialized as a one-dimensional array, and you should use it as a flat array.

Managed 類型Managed type 對等的 JSONJSON equivalent
String(僅限 UTF-8 編碼)。String (UTF-8 encoding only). StringString
Char StringString
單一 null 字元 (例如, \ 0)Single null char (such as, \0 ) NullNull
Boolean 布林值。Boolean. 以 JSON 表示為truefalseRepresented in JSON as true or false
null(null物件參考和Nullable實數值型別)。null (null object references and Nullable value types). Null 的字串值A string value of null
DBNull Null 的字串值A string value of null
基本數值 (或與數值相容) 類型: ByteSByte UInt16 Int16 Int32 Int64 UInt64 Single、、、 、Double、、、和。 UInt32Primitive numeric (or numeric-compatible) types: Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Double, and Single. 使用文化特性-不變字串表示。The culture-invariant string representation is used. numberNumber
DateTime Date 物件, 以 JSON 表示為 "\/Date (刻度數目)\/"。Date object, represented in JSON as "\/Date(number of ticks)\/". 刻度的數目是正數或負的長數值, 指出自1970年1月午夜起經過的刻度數 (毫秒)。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.

支援的最大日期值MaxValue為 (12/31/9999 11:59:59 PM), 而支援的最小MinValue日期值為 (1/1/0001 12:00:00 AM)。The maximum supported date value is MaxValue (12/31/9999 11:59:59 PM) and the minimum supported date value is MinValue (1/1/0001 12:00:00 AM).
整數類型的列舉Enumerations of integer type 列舉值的整數對應項Integer equivalent of the enumeration value
執行IEnumerableSystem.Collections.Generic.IEnumerable<T>的型別, 這些型別也IDictionarySystem.Collections.Generic.IDictionary<TKey,TValue>是或的實現。Types that implement IEnumerable or System.Collections.Generic.IEnumerable<T> that are not also implementations of IDictionary or System.Collections.Generic.IDictionary<TKey,TValue>. 這包括類型Array, 例如、 ArrayList和。 List<T>This includes types such as Array, ArrayList, and List<T>. 使用 JSON 陣列語法的陣列Array that uses JSON array syntax
執行IDictionarySystem.Collections.Generic.IDictionary<TKey,TValue>的類型。Types that implement IDictionary or System.Collections.Generic.IDictionary<TKey,TValue>. 這包括Dictionary<TKey,TValue>Hashtable之類的類型。This includes types such as Dictionary<TKey,TValue> and Hashtable. 使用 JSON 字典語法的 JavaScript 物件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.

請注意, 在這些類型中, 公用唯讀屬性、公用屬性或公用ScriptIgnoreAttribute欄位屬性會被忽略, 而公用索引屬性則會被忽略。Note that public write-only properties, public property or public field attributes marked with ScriptIgnoreAttribute, and public indexed properties in these types are ignored.
使用 JSON 字典語法的 JavaScript 物件。JavaScript object that uses JSON dictionary syntax. 包含名為 "__type" 的特殊中繼資料屬性, 以確保正確的還原序列化。A special metadata property named "__type" is included to ensure correct deserialization. 請確定公用實例屬性具有 get 和 set 存取子, 以確保正確的還原序列化。Make sure that public instance properties have get and set accessors to ensure correct deserialization.
Guid GUID 的字串標記法String representation of a GUID
Uri 傳回值的字串表示GetComponentsString representation of the return value of GetComponents

建構函式

JavaScriptSerializer() JavaScriptSerializer() JavaScriptSerializer() JavaScriptSerializer()

初始化 JavaScriptSerializer 類別的新執行個體,該執行個體沒有類型解析程式。Initializes a new instance of the JavaScriptSerializer class that has no type resolver.

JavaScriptSerializer(JavaScriptTypeResolver) JavaScriptSerializer(JavaScriptTypeResolver) JavaScriptSerializer(JavaScriptTypeResolver) JavaScriptSerializer(JavaScriptTypeResolver)

初始化 JavaScriptSerializer 類別的新執行個體,該執行個體有自訂的類型解析程式。Initializes a new instance of the JavaScriptSerializer class that has a custom type resolver.

屬性

MaxJsonLength MaxJsonLength MaxJsonLength MaxJsonLength

取得或設定 JavaScriptSerializer 類別接受的 JSON 字串最大長度。Gets or sets the maximum length of JSON strings that are accepted by the JavaScriptSerializer class.

RecursionLimit RecursionLimit RecursionLimit RecursionLimit

取得或設定要處理物件層級數目的限制。Gets or sets the limit for constraining the number of object levels to process.

方法

ConvertToType(Object, Type) ConvertToType(Object, Type) ConvertToType(Object, Type) ConvertToType(Object, Type)

將指定的物件轉換成指定的型別。Converts the specified object to the specified type.

ConvertToType<T>(Object) ConvertToType<T>(Object) ConvertToType<T>(Object) ConvertToType<T>(Object)

將指定的物件轉換為指定類型。Converts the given object to the specified type.

Deserialize(String, Type) Deserialize(String, Type) Deserialize(String, Type) Deserialize(String, Type)

將 JSON 格式化字串轉換成指定之類型的物件。Converts a JSON-formatted string to an object of the specified type.

Deserialize<T>(String) Deserialize<T>(String) Deserialize<T>(String) Deserialize<T>(String)

將指定的 JSON 字串轉換成 T 類型的物件。Converts the specified JSON string to an object of type T.

DeserializeObject(String) DeserializeObject(String) DeserializeObject(String) DeserializeObject(String)

將指定的 JSON 字串轉換成物件圖形。Converts the specified JSON string to an object graph.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
RegisterConverters(IEnumerable<JavaScriptConverter>) RegisterConverters(IEnumerable<JavaScriptConverter>) RegisterConverters(IEnumerable<JavaScriptConverter>) RegisterConverters(IEnumerable<JavaScriptConverter>)

JavaScriptSerializer 執行個體註冊自訂轉換子。Registers a custom converter with the JavaScriptSerializer instance.

Serialize(Object) Serialize(Object) Serialize(Object) Serialize(Object)

將物件轉換成 JSON 字串。Converts an object to a JSON string.

Serialize(Object, StringBuilder) Serialize(Object, StringBuilder) Serialize(Object, StringBuilder) Serialize(Object, StringBuilder)

序列化物件並將產生的 JSON 字串寫入指定的 StringBuilder 物件中。Serializes an object and writes the resulting JSON string to the specified StringBuilder object.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

適用於

另請參閱