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异步通信层在内部使用 类来序列化和反序列化在浏览器和 Web 服务器之间传递的数据。 无法访问序列化程序的该实例。 但是,此类公开公共 API。 因此,如果要在托管代码中使用 JavaScript 对象表示法 (JSON) ,可以使用 类。
若要序列化对象,请使用 Serialize 方法。 若要反序列化 JSON 字符串,请使用 Deserialize 或 DeserializeObject 方法。 若要序列化和反序列化本机不支持 JavaScriptSerializer的类型,请使用 类实现自定义转换器 JavaScriptConverter 。 然后使用 方法注册转换器 RegisterConverters 。
托管类型和 JSON 之间的映射
下表显示了序列化过程的托管类型和 JSON 之间的映射。 这些托管类型由 本机支持 JavaScriptSerializer。 将 JSON 字符串反序列化为托管类型时,将应用相同的映射。 但是,反序列化可以是非对称的;并非所有可序列化的托管类型都可以从 JSON 反序列化。
注意
多维数组序列化为一维数组,应将其用作平面数组。
托管类型 | JSON 等效项 |
---|---|
String 仅) (UTF-8 编码。 | 字符串 |
Char | 字符串 |
单个 null 字符 (,例如 \0 ) | Null |
Boolean | 布尔值。 在 JSON 中表示为 true 或 false |
null ) (null 对象引用和 Nullable 值类型。 |
null 的字符串值 |
DBNull | null 的字符串值 |
基元数值 (或与数字兼容的) 类型:Byte、、、Int16、UInt16Int32Int64、UInt32、UInt64、 Double和 。SingleSByte 使用区域性固定字符串表示形式。 | Number |
DateTime | Date 对象,在 JSON 中表示为“\/Date (刻度数) \/”。 计时周期数是正长或负长值,指示自 1970 年 1 月 1 日午夜 1970 年 1 月 1 日 UTC 以来) (毫秒的计时周期数。 支持的最大日期值为 MaxValue) (12/31/9999 晚上 11:59:59,支持的最小日期值为 MinValue) (1/1/0001 12:00:00 AM。 |
整数类型的枚举 | 枚举值的整数等效项 |
实现 IEnumerable 或 System.Collections.Generic.IEnumerable<T> 的类型,这些类型不是 或 System.Collections.Generic.IDictionary<TKey,TValue>的IDictionary实现。 这包括 、 和 List<T>等ArrayArrayList类型。 | 使用 JSON 数组语法的数组 |
实现 IDictionary 或 System.Collections.Generic.IDictionary<TKey,TValue>的类型。 这包括 和 Hashtable等Dictionary<TKey,TValue>类型。 | 使用 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) |