Hướng dẫn serialize javascript

  • Trang chủ
  • Tham khảo
  • jQuery
  • jQuery - function
  • .serialize[]

Định nghĩa và sử dụng

  • .serialize[]: Lấy giá trị các thành phần form, mã hóa các giá trị này thành giá trị chuỗi.
  • Giá trị sẽ được hiển thị theo các cặp cách nhau bởi ký tự "&": name1=value1&name2=value2&...

Cấu trúc

  • Đã được thêm vào từ phiên bản 1.0

.serialize[]

Html viết:




Tiêu đề


$[function[]{
    function showValues[] {
        var str = $["form"].serialize[];
        $["#result"].text[str];
    }
    $["input[type='radio']"].on["click",showValues];
    showValues[];
}];






Male:

Female:

Hiển thị trình duyệt:

Khi click chọn vào radio ta đã lấy được giá trị của các thành phần này thay đổi thông qua cặp giá trị name=value.

Ví dụ thêm

Html viết:




Tiêu đề


$[function[]{
    function showValues[] {
        var str = $["form"].serialize[];
        $["#result"].text[str];
    }
    $["input[type='radio'], input[type='checkbox']"].on["click",showValues];
    $["select"].on["change",showValues];
    showValues[];
}];






Male:

Female:


HTML:
CSS:
JQUERY:

Hà Nội Hồ Chí Minh Nha Trang Cần Thơ

Hiển thị trình duyệt:

Khi thay đổi giá trị của các thành phần trong form, ta sẽ lấy được các giá trị của các thành phần này thông qua các cặp giá trị name1=value1&name2=value2&...

Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

JavaScriptSerializer Class

  • Reference

Definition

For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.Json. This type was intended to provide serialization and deserialization functionality for AJAX-enabled applications.

In this article

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

Examples

The first example provides a simple illustration of how to serialize and deserialize data objects. 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[];
            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[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

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. This code uses a custom converter that is provided for the JavaScriptConverter class.








    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[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;
    }




    Save/Recover state
    
        body {  font: 11pt Trebuchet MS;
                font-color: #000000;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    

    
    
        

Contacts Selection

Type contact's first name:  

Search results:
No data found.
Contacts list:





   Message:   

 Processing...






    
    Dim serializer As JavaScriptSerializer

    Protected Sub Page_Load[ByVal sender As Object, ByVal e As EventArgs]
        '
        serializer = New JavaScriptSerializer[]
    
        ' Register the custom converter.
        serializer.RegisterConverters[New JavaScriptConverter[] _
            {New System.Web.Script.Serialization.VB.ListItemCollectionConverter[]}]
        '
    End Sub

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

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

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

    Protected Sub ContactsGrid_SelectedIndexChanged[ByVal sender As Object, ByVal e As EventArgs]
        ' Get the currently selected row using the SelectedRow property.
        Dim row As GridViewRow = ContactsGrid.SelectedRow
    
        ' Get the ID of the item selected.
        Dim itemId As String = ContactsGrid.DataKeys[row.RowIndex].Value.ToString[]
        Dim newItem As ListItem = New ListItem[row.Cells[4].Text, itemId]

        ' Check if the item already exists in the ListBox control.
        If Not ListBox1.Items.Contains[newItem] Then
            ' Add the item to the ListBox control.
            ListBox1.Items.Add[newItem]
            Message.Text = "Item added"
        Else
            Message.Text = "Item already exists"
        End If
        
    End Sub
 
    Private Function SearchItem[ByVal itemId As String] As Boolean
        Dim i As Integer
        For i = 0 To ListBox1.Items.Count - 1
            If ListBox1.Items[i].Value = itemId Then
                Return True
            End If
        Next i
        Return False

    End Function

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

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

    Protected Sub CheckBox1_CheckedChanged[ByVal sender As Object, ByVal e As EventArgs]
        SavedState.Visible = CheckBox1.Checked
        StateLabel.Visible = CheckBox1.Checked
    End Sub




    Save/Recover state
    
        body {  font: 11pt Trebuchet MS;
                font-color: #000000;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    

    
    
        

Contacts Selection

Type contact's first name:  

Search results:
No data found.
Contacts list:





   Message:   

 Processing...

Remarks

Important

For .NET Framework 4.7.2 and later versions, the APIs in the System.Text.Json namespace should be used for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.Json.

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.

Note

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

Managed typeJSON 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: Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Double, and 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 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 that are not also implementations of IDictionary or System.Collections.Generic.IDictionary. This includes types such as Array, ArrayList, and List. Array that uses JSON array syntax
Types that implement IDictionary or System.Collections.Generic.IDictionary. This includes types such as Dictionary 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.
Guid String representation of a GUID
Uri String representation of the return value of GetComponents

Constructors

Properties

Methods

ConvertToType[Object, Type]

Converts the specified object to the specified type.

ConvertToType[Object]

Converts the given object to the specified type.

Deserialize[String, Type]

Converts a JSON-formatted string to an object of the specified type.

Deserialize[String]

Converts the specified JSON string to an object of type T.

DeserializeObject[String]

Converts the specified JSON string to an object graph.

Equals[Object]

Determines whether the specified object is equal to the current object.

[Inherited from Object]
GetHashCode[]

Serves as the default hash function.

[Inherited from Object]
GetType[]

Gets the Type of the current instance.

[Inherited from Object]
MemberwiseClone[]

Creates a shallow copy of the current Object.

[Inherited from Object]
RegisterConverters[IEnumerable]

Registers a custom converter with the JavaScriptSerializer instance.

Serialize[Object]

Converts an object to a JSON string.

Serialize[Object, StringBuilder]

Serializes an object and writes the resulting JSON string to the specified StringBuilder object.

ToString[]

Returns a string that represents the current object.

[Inherited from Object]

Applies to

See also

  • Using Web Services in ASP.NET AJAX
  • Calling Web Services from Client Script in ASP.NET AJAX

Chủ Đề