序列化 (C#)Serialization (C#)

序列化是指将对象转换成字节流,从而存储对象或将对象传输到内存、数据库或文件的过程。Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. 它的主要用途是保存对象的状态,以便能够在需要时重新创建对象。Its main purpose is to save the state of an object in order to be able to recreate it when needed. 反向过程称为“反序列化”。The reverse process is called deserialization.

序列化的工作原理How serialization works

下图展示了序列化的整个过程:This illustration shows the overall process of serialization:

图:序列化

将对象序列化为带有数据的流。The object is serialized to a stream that carries the data. 该流还可能包含有关对象类型的信息,例如其版本、区域性和程序集名称。The stream may also have information about the object's type, such as its version, culture, and assembly name. 可以将此流中的对象存储在数据库、文件或内存中。From that stream, the object can be stored in a database, a file, or memory.

序列化的用途Uses for serialization

通过序列化,开发人员可以保存对象的状态,并能在需要时重新创建对象,同时还能存储对象和交换数据。Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. 通过序列化,开发人员可以执行如下操作:Through serialization, a developer can perform actions such as:

  • 使用 Web 服务将对象发送到远程应用程序Sending the object to a remote application by using a web service
  • 将对象从一个域传递到另一个域Passing an object from one domain to another
  • 将对象通过防火墙传递为 JSON 或 XML 字符串Passing an object through a firewall as a JSON or XML string
  • 跨应用程序维护安全或用户特定的信息Maintaining security or user-specific information across applications

JSON 序列化JSON serialization

System.Text.Json 命名空间包含用于 JavaScript 对象表示法 (JSON) 序列化和反序列化的类。The System.Text.Json namespace contains classes for JavaScript Object Notation (JSON) serialization and deserialization. JSON 是一种常用于在 Web 上共享数据的开放标准。JSON is an open standard that is commonly used for sharing data across the web.

JSON 序列化将对象的公共属性序列化为符合 RFC 8259 JSON 规范的字符串、字节数组或流。JSON serialization serializes the public properties of an object into a string, byte array, or stream that conforms to the RFC 8259 JSON specification. 若要控制 JsonSerializer 对类的实例进行序列化或反序列化的方法,请执行以下操作:To control the way JsonSerializer serializes or deserializes an instance of the class:

二进制和 XML 序列化Binary and XML serialization

System.Runtime.Serialization 命名空间包含用于对二进制和 XML 进行序列化和反序列化的类。The System.Runtime.Serialization namespace contains classes for binary and XML serialization and deserialization.

二进制序列化使用二进制编码来生成精简的序列化以供使用,如基于存储或套接字的网络流。Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network streams. 在二进制序列化中,所有成员(包括只读成员)都会被序列化,且性能也会有所提升。In binary serialization, all members, even members that are read-only, are serialized, and performance is enhanced.

警告

二进制序列化可能会十分危险。Binary serialization can be dangerous. 有关详细信息,请参阅BinaryFormatter security guideFor more information, see BinaryFormatter security guide.

XML 序列化将对象的公共字段和属性或方法的参数和返回值序列化成符合特定 XML 架构定义语言 (XSD) 文档要求的 XML 流。XML serialization serializes the public fields and properties of an object, or the parameters and return values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML 序列化生成已转换成 XML 的强类型类,其中包含公共属性和字段。XML serialization results in strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization 包含用于对 XML 进行序列化和反序列化的类。System.Xml.Serialization contains classes for serializing and deserializing XML. 将特性应用于类和类成员,从而控制 XmlSerializer 如何序列化或反序列化类的实例。You apply attributes to classes and class members to control the way the XmlSerializer serializes or deserializes an instance of the class.

让对象可序列化Making an object serializable

若要对二进制或 XML 进行序列化,你需要:For binary or XML serialization, you need:

SerializableAttribute 特性应用于某个类型,以指示可对此类型进行序列化的实例。Apply the SerializableAttribute attribute to a type to indicate that instances of the type can be serialized. 如果尝试对没有 SerializableAttribute 特性的类型进行序列化,则会引发异常。An exception is thrown if you attempt to serialize but the type doesn't have the SerializableAttribute attribute.

若要防止对字段进行序列化,请应用 NonSerializedAttribute 特性。To prevent a field from being serialized, apply the NonSerializedAttribute attribute. 如果可序列化的类型中的一个字段包含指针、句柄或特定环境专用的其他一些数据结构,且不能在其他环境中有意义地重构,不妨让其不可序列化。If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and the field cannot be meaningfully reconstituted in a different environment, then you may want to make it nonserializable.

如果已序列化的类引用被标记为 SerializableAttribute 的其他类的对象,那么这些对象也会被序列化。If a serialized class contains references to objects of other classes that are marked SerializableAttribute, those objects will also be serialized.

基本和自定义序列化Basic and custom serialization

可以使用两种方法对二进制和 XML 进行序列化:基本和自定义。Binary and XML serialization can be performed in two ways, basic and custom.

基本序列化使用 .NET 自动序列化对象。Basic serialization uses .NET to automatically serialize the object. 唯一的要求是类应用 SerializableAttribute 特性。The only requirement is that the class has the SerializableAttribute attribute applied. NonSerializedAttribute 可用于防止特定字段被序列化。The NonSerializedAttribute can be used to keep specific fields from being serialized.

使用基本序列化时,对象的版本控制可能会产生问题。When you use basic serialization, the versioning of objects may create problems. 对于重要的版本控制问题,可以使用自定义序列化。You would use custom serialization when versioning issues are important. 基本序列化是最简单的序列化执行方式,但无法提供太多的进程控制。Basic serialization is the easiest way to perform serialization, but it does not provide much control over the process.

在自定义序列化中,可以精确指定要序列化的对象以及具体执行方式。In custom serialization, you can specify exactly which objects will be serialized and how it will be done. 类必须被标记为 SerializableAttribute,并实现 ISerializable 接口。The class must be marked SerializableAttribute and implement the ISerializable interface. 如果还希望按自定义方式反序列化对象,请使用自定义构造函数。If you want your object to be deserialized in a custom manner as well, use a custom constructor.

设计器序列化Designer serialization

设计器序列化是一种特殊形式的序列化,涉及与开发工具相关联的对象暂留。Designer serialization is a special form of serialization that involves the kind of object persistence associated with development tools. 设计器序列化是指将对象图转换成源文件以供日后用于恢复对象图的过程。Designer serialization is the process of converting an object graph into a source file that can later be used to recover the object graph. 源文件可以包含代码、标记或 SQL 表信息。A source file can contain code, markup, or even SQL table information.

System.Text.Json 概述 演示如何获取 System.Text.Json 库。System.Text.Json overview Shows how to get the System.Text.Json library.

如何在 .NET 中对 JSON 数据进行序列化和反序列化How to serialize and deserialize JSON in .NET. 演示如何使用 JsonSerializer 类在 JSON 之间读取和写入对象数据。Shows how to read and write object data to and from JSON using the JsonSerializer class.

演练:在 Visual Basic 中保持对象 (C#)Walkthrough: Persisting an Object in Visual Studio (C#)
展示了如何使用序列化在实例之间暂留对象数据,以便可以存储值并在下次实例化对象时检索值。Demonstrates how serialization can be used to persist an object's data between instances, allowing you to store values and retrieve them the next time the object is instantiated.

如何从 XML 文件读取对象数据 (C#)How to read object data from an XML file (C#)
介绍如何使用 XmlSerializer 类读取之前写入 XML 文件的对象数据。Shows how to read object data that was previously written to an XML file using the XmlSerializer class.

如何将对象数据写入 XML 文件 (C#)How to write object data to an XML file (C#)
介绍如何使用 XmlSerializer 类从某个类将对象写入 XML 文件。Shows how to write the object from a class to an XML file using the XmlSerializer class.