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>
備註
Important
在 .NET Framework 4.7.2 及更新版本中,應使用 System.Text.Json 命名空間中的 API,用於序列化與反序列化。 對於較早期版本的 .NET Framework,請使用 Newtonsoft.Json。
此 JavaScriptSerializer 類別由非同步通訊層內部使用,用於序列化與反序列化瀏覽器與網頁伺服器間傳遞的資料。 你無法存取那個序列化器的實例。 然而,這個類別會暴露一個公開 API。 因此,當你想在管理程式碼中使用 JavaScript 物件符號(JSON)時,可以使用這個類別。
要序列化物件,請使用以下 Serialize 方法。 要反序列化 JSON 字串,請使用 Deserialize or DeserializeObject 方法。 若要序列化與反序列化那些未原生支援的 JavaScriptSerializer型別,請使用 JavaScriptConverter 類別實作自訂轉換器。 然後用這個 RegisterConverters 方法註冊轉換器。
管理型別與 JSON 之間的映射
下表展示了受管理型別與序列化流程 JSON 之間的對應。 這些受管理型態原生支援。JavaScriptSerializer 當你從 JSON 字串反序列化成受管理型別時,映射方式也是一樣的。 然而,反序列化可能是非對稱的;並非所有可序列化的受管理型態都能從 JSON 反序列化。
Note
多維陣列會序列化為一維陣列,你應該用它作為平面陣列。
| 管理的類型 | JSON 等價物 |
|---|---|
| String (僅 UTF-8 編碼)。 | String |
| Char | String |
| 單一零字元(例如 \0) | 無效 |
| Boolean | 布林值。 以 JSON 表示為 true 或 false |
null (null 物件參考與 Nullable 值型別)。 |
字串值為 null |
| DBNull | 字串值為 null |
| 原始數值型(或數值相容型態):, ByteSByte, Int16Int32UInt64Int64UInt16UInt32Double。Single 使用文化不變的字串表示法。 | 編號 |
| DateTime | Date 物件,在 JSON 中表示為「\/Date(tick 數量)\/」。 tick 數量為正或負的多數值,表示自 1970 年 1 月 1 日午夜(UTC)以來已經過的 tick 數(毫秒)。 最大支援日期值為 MaxValue (12/31/999 11:59:59 PM),最小支援日期值為 MinValue (1/1/000 AM 12:00:00)。 |
| 整數型列舉 | 整數等價於列舉值 |
| 實作或非實作IEnumerableSystem.Collections.Generic.IEnumerable<T>的類型也為或System.Collections.Generic.IDictionary<TKey,TValue>的實作IDictionary。 這包括 、 ArrayList、 List<T>等類型Array。 | 使用 JSON 陣列語法的陣列 |
| 實作 IDictionary 或 System.Collections.Generic.IDictionary<TKey,TValue>的類型。 這包括像 Dictionary<TKey,TValue> 和 Hashtable這樣的類型。 | 使用 JSON 字典語法的 JavaScript 物件 |
| 自訂的具體(非抽象)類型,具有 public instance 屬性,例如 get accessor 或 public instance fields。 請注意,這些類型中僅寫入的公共屬性、標記為 ScriptIgnoreAttribute的公共屬性或公共欄位屬性,以及這些類型中的公開索引屬性都被忽略。 |
JavaScript 物件使用 JSON 字典語法。 內建一個名為「__type」的特殊元資料屬性,以確保正確的反序列化。 確保公開實例屬性有 get 和 set 的 accessr,以確保正確的反序列化。 |
| Guid | GUID 的字串表示法 |
| Uri | 回傳值的字串表示 GetComponents |
建構函式
| 名稱 | Description |
|---|---|
| JavaScriptSerializer() |
初始化一個沒有型別解析器的類別新實例 JavaScriptSerializer 。 |
| JavaScriptSerializer(JavaScriptTypeResolver) |
初始化一個擁有自訂型別解析器的類別新實例 JavaScriptSerializer 。 |
屬性
| 名稱 | Description |
|---|---|
| MaxJsonLength |
取得或設定類別接受 JavaScriptSerializer 的最大 JSON 字串長度。 |
| RecursionLimit |
取得或設定限制處理物件層級數量的限制。 |
方法
| 名稱 | Description |
|---|---|
| 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, StringBuilder) |
序列化一個物件,並將產生的 JSON 字串寫入指定的 StringBuilder 物件。 |
| Serialize(Object) |
將物件轉換成 JSON 字串。 |
| ToString() |
傳回表示目前 物件的字串。 (繼承來源 Object) |