JavaScriptSerializer 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
針對 .NET Framework 4.7.2 和更新版本,請使用 命名空間中的 System.Text.Json API 進行串行化和還原串行化。 針對舊版的 .NET Framework,請使用 Newtonsoft.Json。 此類型旨在提供啟用 AJAX 之應用程式的串行化和還原串行化功能。
public ref class JavaScriptSerializer
public class JavaScriptSerializer
type JavaScriptSerializer = class
Public Class JavaScriptSerializer
- 繼承
-
JavaScriptSerializer
範例
第一個範例提供如何串行化和還原串行化數據對象的簡單圖例。 它需要名為 Person 的類別,如下所示。
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 串行化。 此程式代碼會使用提供給 類別的 JavaScriptConverter 自定義轉換器。
<%@ 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" />
<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 />
<hr />
Message: <asp:Label ID="Message" runat="server" ForeColor="SteelBlue" /> <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" /> 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" />
<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 />
<hr />
Message: <asp:Label ID="Message" runat="server" ForeColor="SteelBlue" /> <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" /> Processing...
</ProgressTemplate>
</asp:UpdateProgress>
</form>
</body>
</html>
備註
重要
針對 .NET Framework 4.7.2 和更新版本,命名空間中的 System.Text.Json API 應該用於串行化和還原串行化。 針對舊版的 .NET Framework,請使用 Newtonsoft.Json。
異步 JavaScriptSerializer 通訊層會在內部使用 類別,以串行化和還原串行化瀏覽器與網頁伺服器之間傳遞的數據。 您無法存取串行化程序的實例。 不過,這個類別會公開公用 API。 因此,當您想要在 Managed 程式代碼中使用 JavaScript 物件表示法 (JSON) 時,可以使用 類別。
若要串行化物件,請使用 Serialize 方法。 若要還原串行化 JSON 字串,請使用 Deserialize 或 DeserializeObject 方法。 若要串行化和還原串行化原本不支援 JavaScriptSerializer的類型,請使用 類別實作 JavaScriptConverter 自定義轉換器。 然後使用 方法註冊轉換器 RegisterConverters 。
Managed 類型和 JSON 之間的對應
下表顯示串行化程式Managed類型和 JSON 之間的對應。 這些 Managed 類型原生支援 JavaScriptSerializer。 當您從 JSON 字串還原串行化為 Managed 類型時,會套用相同的對應。 不過,還原串行化可以是非對稱的;並非所有可串行化的Managed類型都可以從 JSON 還原串行化。
注意
多維度陣列會串行化為一維陣列,您應該使用它作為一般陣列。
Managed 類型 | JSON 對等專案 |
---|---|
String 僅) (UTF-8 編碼。 | String |
Char | String |
單一 null char (,例如 \0 ) | Null |
Boolean | 布林值。 以 JSON 表示為 true 或 false |
null
null (對象參考和Nullable實值型別) 。 |
null 的字串值 |
DBNull | null 的字串值 |
基本數值 (或與數值相容的) 類型:Byte、SByte、Int64UInt16Int16Int32、、UInt32、 UInt64Double和 。Single 使用 culture-invariant 字串表示。 | Number |
DateTime | 日期物件,以 JSON 表示為 “\/Date () \/” 的刻度數目。 刻度數是正數或負長值,表示自 1970 年 1 月 1 日午夜 1 月 01 日起經過的刻度數) (毫秒數。 支援的日期值上限為 MaxValue (12/31/9999 下午 11:59:59) ,而支援的最小日期值 (MinValue 上午 1/1/0001 上午 12:00:00:00) 。 |
整數類型的列舉 | 列舉值的整數對等專案 |
實IEnumerable作 或不是 System.Collections.Generic.IEnumerable<T> 或 System.Collections.Generic.IDictionary<TKey,TValue>實作的類型IDictionary。 這包括、、 和 List<T>等ArrayArrayList類型。 | 使用 JSON 陣列語法的陣列 |
實 IDictionary 作 或 System.Collections.Generic.IDictionary<TKey,TValue>的類型。 這包括和 之類的Dictionary<TKey,TValue>Hashtable類型。 | 使用 JSON 字典語法的 JavaScript 物件 |
具有具有 get 存取子或公用實例欄位之公用實例屬性的自定義具體 (非抽象) 類型。 請注意,這些類型中標示 ScriptIgnoreAttribute為的公用寫入屬性、公用屬性或公用欄位屬性,以及這些類型的公用索引屬性都會被忽略。 |
使用 JSON 字典語法的 JavaScript 物件。 包含名為 「__type」 的特殊元資料屬性,以確保正確還原串行化。 請確定公用實例屬性具有 get 和 set 存取子,以確保正確的還原串行化。 |
Guid | GUID 的字串表示 |
Uri | 傳回值的字串表示 GetComponents |
建構函式
JavaScriptSerializer() |
初始化 JavaScriptSerializer 類別的新執行個體,該執行個體沒有類型解析程式。 |
JavaScriptSerializer(JavaScriptTypeResolver) |
初始化 JavaScriptSerializer 類別的新執行個體,該執行個體有自訂的類型解析程式。 |
屬性
MaxJsonLength |
取得或設定 JavaScriptSerializer 類別接受的 JSON 字串最大長度。 |
RecursionLimit |
取得或設定要處理物件層級數目的限制。 |
方法
ConvertToType(Object, Type) |
將指定的物件轉換成指定的類型。 |
ConvertToType<T>(Object) |
將指定的物件轉換為指定類型。 |
Deserialize(String, Type) |
將 JSON 格式化字串轉換成指定之類型的物件。 |
Deserialize<T>(String) |
將指定的 JSON 字串轉換成 |
DeserializeObject(String) |
將指定的 JSON 字串轉換成物件圖形。 |
Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
GetHashCode() |
做為預設雜湊函式。 (繼承來源 Object) |
GetType() |
取得目前執行個體的 Type。 (繼承來源 Object) |
MemberwiseClone() |
建立目前 Object 的淺層複製。 (繼承來源 Object) |
RegisterConverters(IEnumerable<JavaScriptConverter>) |
向 JavaScriptSerializer 執行個體註冊自訂轉換子。 |
Serialize(Object) |
將物件轉換成 JSON 字串。 |
Serialize(Object, StringBuilder) |
序列化物件並將產生的 JSON 字串寫入指定的 StringBuilder 物件中。 |
ToString() |
傳回代表目前物件的字串。 (繼承來源 Object) |