JavaScriptSerializer Klasse

Definition

Verwenden Sie für .NET Framework 4.7.2 und spätere Versionen die APIs im- System.Text.Json Namespace für die Serialisierung und Deserialisierung.For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. Verwenden Sie für frühere Versionen von .NET Framework Newtonsoft.Json.For earlier versions of .NET Framework, use Newtonsoft.Json. Dieser Typ wurde zum Bereitstellen von Serialisierungs-und Deserialisierungsfunktionen für AJAX-aktivierte Anwendungen vorgesehen.This type was intended to provide serialization and deserialization functionality for AJAX-enabled applications.

public ref class JavaScriptSerializer
public class JavaScriptSerializer
type JavaScriptSerializer = class
Public Class JavaScriptSerializer
Vererbung
JavaScriptSerializer

Beispiele

Im ersten Beispiel wird eine einfache Abbildung der Serialisierung und Deserialisierung von Datenobjekten veranschaulicht.The first example provides a simple illustration of how to serialize and deserialize data objects. Hierfür ist eine Klasse namens "Person" erforderlich, die unten dargestellt ist.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

Das nächste Beispiel zeigt ein komplizierteres und ausführlichere Projekt, das die JavaScriptSerializer -Klasse verwendet, um den Zustand eines Objekts mithilfe der JSON-Serialisierung zu speichern und wiederherzustellen.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. In diesem Code wird ein benutzerdefinierter Konverter verwendet, der für die-Klasse bereitgestellt wird 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>

Hinweise

Wichtig

Für .NET Framework 4.7.2 und spätere Versionen sollten die APIs im- System.Text.Json Namespace für die Serialisierung und Deserialisierung verwendet werden.For .NET Framework 4.7.2 and later versions, the APIs in the System.Text.Json namespace should be used for serialization and deserialization. Verwenden Sie für frühere Versionen von .NET Framework Newtonsoft.Json.For earlier versions of .NET Framework, use Newtonsoft.Json.

Die JavaScriptSerializer -Klasse wird intern von der asynchronen Kommunikationsschicht verwendet, um die Daten zu serialisieren und zu deserialisieren, die zwischen dem Browser und dem Webserver übermittelt werden.The 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. Sie können nicht auf diese Instanz des Serialisierungsprogramms zugreifen.You cannot access that instance of the serializer. Diese Klasse macht jedoch eine öffentliche API verfügbar.However, this class exposes a public API. Daher können Sie die-Klasse verwenden, wenn Sie mit JavaScript Object Notation (JSON) in verwaltetem Code arbeiten möchten.Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.

Verwenden Sie die-Methode, um ein Objekt zu serialisieren Serialize .To serialize an object, use the Serialize method. Verwenden Sie zum Deserialisieren einer JSON-Zeichenfolge die- Deserialize Methode oder die- DeserializeObject Methode.To deserialize a JSON string, use the Deserialize or DeserializeObject methods. Zum Serialisieren und Deserialisieren von Typen, die nicht System intern von unterstützt werden JavaScriptSerializer , implementieren Sie benutzerdefinierte Konverter mithilfe der- JavaScriptConverter Klasse.To serialize and deserialize types that are not natively supported by JavaScriptSerializer, implement custom converters by using the JavaScriptConverter class. Registrieren Sie dann die Konverter mithilfe der- RegisterConverters Methode.Then register the converters by using the RegisterConverters method.

Zuordnung zwischen verwalteten Typen und JSONMapping Between Managed Types and JSON

Die folgende Tabelle zeigt die Zuordnung zwischen verwalteten Typen und JSON für den Serialisierungsprozess.The following table shows the mapping between managed types and JSON for the serialization process. Diese verwalteten Typen werden von nativ unterstützt JavaScriptSerializer .These managed types are natively supported by JavaScriptSerializer. Wenn Sie von einer JSON-Zeichenfolge in einen verwalteten Typ deserialisieren, gilt dieselbe Zuordnung.When you are deserializing from a JSON string to a managed type, the same mapping applies. Die Deserialisierung kann jedoch asymmetrisch sein. nicht alle serialisierbaren verwalteten Typen können aus JSON deserialisiert werden.However, deserialization can be asymmetric; not all serializable managed types can be deserialized from JSON.

Hinweis

Ein mehrdimensionales Array wird als eindimensionales Array serialisiert, und Sie sollten es als flaches Array verwenden.A multidimensional array is serialized as a one-dimensional array, and you should use it as a flat array.

Verwalteter TypManaged type JSON-EntsprechungJSON equivalent
String (Nur UTF-8-Codierung).String (UTF-8 encoding only). StringString
Char StringString
Einzelnes Null char (z. b., \ 0)Single null char (such as, \0 ) NullNull
Boolean Boolesch.Boolean. In JSON als true oder dargestellt falseRepresented in JSON as true or false
null ( null Objekt Verweise und Nullable Werttypen).null (null object references and Nullable value types). Ein Zeichen folgen Wert von NULL.A string value of null
DBNull Ein Zeichen folgen Wert von NULL.A string value of null
Primitive numerische (oder numerisch kompatible) Typen: Byte , SByte , Int16 , Int32 , Int64 , UInt16 , UInt32 , UInt64 , Double und Single .Primitive numeric (or numeric-compatible) types: Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Double, and Single. Die Kultur unveränderliche Zeichen folgen Darstellung wird verwendet.The culture-invariant string representation is used. NumberNumber
DateTime Date-Objekt, dargestellt in JSON als " \ /Date (Anzahl der Ticks) \ /".Date object, represented in JSON as "\/Date(number of ticks)\/". Die Anzahl der Ticks ist ein positiver oder negativer Long-Wert, der die Anzahl der Ticks (Millisekunden) angibt, die seit Mitternacht 01. Januar 1970 UTC verstrichen sind.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.

Der maximal unterstützte Datumswert ist MaxValue (12/31/9999 11:59:59 Uhr), und der minimale unterstützte Datumswert ist MinValue (1/1/0001 12:00:00 Uhr).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).
Enumerationen des ganzzahligen TypsEnumerations of integer type Ganzzahlige Entsprechung des-EnumerationswertsInteger equivalent of the enumeration value
Typen, die IEnumerable oder implementieren und System.Collections.Generic.IEnumerable<T> nicht auch Implementierungen von IDictionary oder sind System.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>. Dies schließt Typen wie Array , ArrayList und ein List<T> .This includes types such as Array, ArrayList, and List<T>. Array, das JSON-Array Syntax verwendetArray that uses JSON array syntax
Typen, die IDictionary oder implementieren System.Collections.Generic.IDictionary<TKey,TValue> .Types that implement IDictionary or System.Collections.Generic.IDictionary<TKey,TValue>. Dies schließt Typen wie Dictionary<TKey,TValue> und ein Hashtable .This includes types such as Dictionary<TKey,TValue> and Hashtable. JavaScript-Objekt, das JSON-Wörterbuch Syntax verwendetJavaScript object that uses JSON dictionary syntax
Benutzerdefinierte konkrete (nicht abstrakte) Typen mit öffentlichen Instanzeigenschaften, die über Get-Accessoren oder öffentliche Instanzfelder verfügen.Custom concrete (non-abstract) types that have public instance properties that have get accessors or public instance fields.

Beachten Sie, dass öffentliche schreibgeschützte Eigenschaften, öffentliche Eigenschaften oder öffentliche Feld Attribute, ScriptIgnoreAttribute die mit gekennzeichnet sind, und öffentliche indizierte Eigenschaften in diesen Typen ignoriert werden.Note that public write-only properties, public property or public field attributes marked with ScriptIgnoreAttribute, and public indexed properties in these types are ignored.
JavaScript-Objekt, das die JSON-Wörterbuch Syntax verwendet.JavaScript object that uses JSON dictionary syntax. Eine spezielle Metadateneigenschaft mit dem Namen "__type" ist enthalten, um die korrekte Deserialisierung sicherzustellen.A special metadata property named "__type" is included to ensure correct deserialization. Stellen Sie sicher, dass Public instance Properties über Get-und Set-Accessoren verfügen, um eine korrekte Deserialisierung sicherzustellen.Make sure that public instance properties have get and set accessors to ensure correct deserialization.
Guid Zeichen folgen Darstellung einer GUIDString representation of a GUID
Uri Zeichen folgen Darstellung des Rückgabewerts von GetComponentsString representation of the return value of GetComponents

Konstruktoren

JavaScriptSerializer()

Initialisiert eine neue Instanz der JavaScriptSerializer-Klasse, die über keinen Typresolver verfügt.Initializes a new instance of the JavaScriptSerializer class that has no type resolver.

JavaScriptSerializer(JavaScriptTypeResolver)

Initialisiert eine neue Instanz der JavaScriptSerializer-Klasse, die über einen benutzerdefinierten Typresolver verfügt.Initializes a new instance of the JavaScriptSerializer class that has a custom type resolver.

Eigenschaften

MaxJsonLength

Ruft die maximale Länge von JSON-Zeichenfolgen ab, die von der JavaScriptSerializer-Klasse akzeptiert werden, oder legt diese fest.Gets or sets the maximum length of JSON strings that are accepted by the JavaScriptSerializer class.

RecursionLimit

Ruft den Grenzwert für die Anzahl von Objektebenen für die Verarbeitung ab oder legt diesen fest.Gets or sets the limit for constraining the number of object levels to process.

Methoden

ConvertToType(Object, Type)

Konvertiert das angegebene Objekt in den angegebenen Typ.Converts the specified object to the specified type.

ConvertToType<T>(Object)

Konvertiert das angegebene Objekt in den angegebenen Typ.Converts the given object to the specified type.

Deserialize(String, Type)

Konvertiert eine JSON-formatierte Zeichenfolge in ein Objekt des angegebenen Typs.Converts a JSON-formatted string to an object of the specified type.

Deserialize<T>(String)

Konvertiert die angegebene JSON-Zeichenfolge in ein Objekt vom Typ T.Converts the specified JSON string to an object of type T.

DeserializeObject(String)

Konvertiert die angegebene JSON-Zeichenfolge in ein Objektdiagramm.Converts the specified JSON string to an object graph.

Equals(Object)

Bestimmt, ob das angegebene Objekt gleich dem aktuellen Objekt ist.Determines whether the specified object is equal to the current object.

(Geerbt von Object)
GetHashCode()

Fungiert als Standardhashfunktion.Serves as the default hash function.

(Geerbt von Object)
GetType()

Ruft den Type der aktuellen Instanz ab.Gets the Type of the current instance.

(Geerbt von Object)
MemberwiseClone()

Erstellt eine flache Kopie des aktuellen Object.Creates a shallow copy of the current Object.

(Geerbt von Object)
RegisterConverters(IEnumerable<JavaScriptConverter>)

Registriert bei der Instanz von JavaScriptSerializer einen benutzerdefinierten Konverter.Registers a custom converter with the JavaScriptSerializer instance.

Serialize(Object)

Konvertiert ein Objekt in eine JSON-Zeichenfolge.Converts an object to a JSON string.

Serialize(Object, StringBuilder)

Serialisiert ein Objekt und schreibt die resultierende JSON-Zeichenfolge in das angegebene StringBuilder-Objekt.Serializes an object and writes the resulting JSON string to the specified StringBuilder object.

ToString()

Gibt eine Zeichenfolge zurück, die das aktuelle Objekt darstellt.Returns a string that represents the current object.

(Geerbt von Object)

Gilt für: