This documentation is archived and is not being maintained.

JavaScriptSerializer Class

Provides serialization and deserialization functionality for AJAX-enabled applications.


Namespace:  System.Web.Script.Serialization
Assembly:  System.Web.Extensions (in System.Web.Extensions.dll)

public class JavaScriptSerializer

The JavaScriptSerializer type exposes the following members.

Public methodJavaScriptSerializer()Initializes a new instance of the JavaScriptSerializer class that has no type resolver.
Public methodJavaScriptSerializer(JavaScriptTypeResolver)Initializes a new instance of the JavaScriptSerializer class that has a custom type resolver.

Public propertyMaxJsonLengthGets or sets the maximum length of JSON strings that are accepted by the JavaScriptSerializer class.
Public propertyRecursionLimitGets or sets the limit for constraining the number of object levels to process.

Public methodConvertToType(Object, Type)Converts the specified object to the specified type.
Public methodConvertToType<T>(Object)Converts the given object to the specified type.
Public methodDeserialize(String, Type)Converts a JSON-formatted string to an object of the specified type.
Public methodDeserialize<T>(String)Converts the specified JSON string to an object of type T.
Public methodDeserializeObjectConverts the specified JSON string to an object graph.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodRegisterConvertersRegisters a custom converter with the JavaScriptSerializer instance.
Public methodSerialize(Object)Converts an object to a JSON string.
Public methodSerialize(Object, StringBuilder)Serializes an object and writes the resulting JSON string to the specified StringBuilder object.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)

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. 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 Serialize method. To deserialize a JSON string, use the Deserialize or DeserializeObject methods. To serialize and deserialize types that are not natively supported by JavaScriptSerializer, implement custom converters by using the JavaScriptConverter class. Then register the converters by using the RegisterConverters method.

Mapping Between Managed Types and JSON

The following table shows the mapping between managed types and JSON for the serialization process. These managed types are natively supported by 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.


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).




Single null char (such as, \0 )



Boolean. Represented in JSON as true or false

null (null object references and Nullable value types).

A string value of null


A string value of null

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



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 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

Types that implement IEnumerable or System.Collections.Generic.IEnumerable<T> that are not also implementations of IDictionary or System.Collections.Generic.IDictionary<TKey, TValue>. This includes types such as Array, ArrayList, and List<T>.

Array that uses JSON array syntax

Types that implement IDictionary or System.Collections.Generic.IDictionary<TKey, TValue>. This includes types such as Dictionary<TKey, TValue> and 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 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.


String representation of a GUID


String representation of the return value of GetComponents

The following example shows how to use the 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 JavaScriptConverter class.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<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() });

    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);
        Message.Text = "Last saved state recovered.";

    protected void clearButton_Click(object sender, EventArgs e)
        // Remove all items from the ListBox control.
        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.
            Message.Text = "Item added";
            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.

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

<html xmlns="" >
<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 }
    <form id="form1" runat="server" defaultbutton="searchButton" defaultfocus="TextBox1">
            <span style="text-decoration: underline">
                                    Contacts Selection</span><br />
        <asp:ScriptManager runat="server" ID="ScriptManager1" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                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%">
                        <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">
                                    <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" />
                                <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:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
                                SelectCommand="SELECT ContactID, FirstName, LastName, EmailAddress FROM Person.Contact WHERE (UPPER(FirstName) = UPPER(@FIRSTNAME))" >
                                    <asp:ControlParameter Name="FIRSTNAME" ControlId="TextBox1" Type="String" />
                        <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>
                        <td colspan="2">
                            <br />
                            <br />
                            <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 />                        
        <asp:UpdateProgress ID="UpdateProgress1" runat="server">
                <asp:Image ID="Image1" runat="server" ImageUrl="..\images\spinner.gif" />&nbsp;Processing...

.NET Framework

Supported in: 4, 3.5

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.