《C# 的三种序列化方法》
在C# (.NET)开发中,序列化(Serialization)是将对象转换为可存储或传输格式(如二进制、JSON、XML)的过程,反序列化(Deserialization)则是将格式化数据还原为对象的过程。序列化广泛应用于数据持久化、网络通信、缓存存储等场景。本文将详细介绍C#中三种主流的序列化方法:二进制序列化、XML序列化和JSON序列化,分析它们的原理、优缺点及适用场景,并提供完整的代码示例。
一、二进制序列化
二进制序列化将对象转换为紧凑的二进制格式,保留对象的完整类型信息,包括私有字段和程序集版本。它是.NET Framework中最早支持的序列化方式,适用于需要高效存储或传输的场景。
1.1 基本实现
使用`System.Runtime.Serialization.Formatters.Binary`命名空间中的`BinaryFormatter`类实现二进制序列化:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class BinarySerializationDemo
{
public static void Serialize()
{
var person = new Person { Name = "Alice", Age = 30 };
var formatter = new BinaryFormatter();
using (var stream = new FileStream("person.bin", FileMode.Create))
{
formatter.Serialize(stream, person);
}
Console.WriteLine("二进制序列化完成");
}
public static void Deserialize()
{
var formatter = new BinaryFormatter();
using (var stream = new FileStream("person.bin", FileMode.Open))
{
var person = (Person)formatter.Deserialize(stream);
Console.WriteLine($"反序列化结果: Name={person.Name}, Age={person.Age}");
}
}
}
关键点:
- 被序列化的类必须标记`[Serializable]`特性
- 不支持跨平台(.NET Core 3.1+已标记为不安全,建议使用替代方案)
- 序列化结果不可读,但体积小、速度快
1.2 安全问题与替代方案
微软已将`BinaryFormatter`标记为不安全,因其存在反序列化漏洞。推荐替代方案:
System.Text.Json二进制扩展(.NET 5+):
using System.Text.Json;
using System.IO;
public class SafeBinaryDemo
{
public static void Serialize()
{
var person = new Person { Name = "Bob", Age = 25 };
var options = new JsonSerializerOptions { WriteIndented = true };
var json = JsonSerializer.Serialize(person, options);
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
File.WriteAllBytes("person_safe.bin", bytes);
}
public static void Deserialize()
{
var bytes = File.ReadAllBytes("person_safe.bin");
var json = System.Text.Encoding.UTF8.GetString(bytes);
var person = JsonSerializer.Deserialize(json);
Console.WriteLine($"安全反序列化: Name={person.Name}");
}
}
二、XML序列化
XML序列化将对象转换为符合XML标准的文本格式,具有良好的可读性和跨平台性。.NET提供了`System.Xml.Serialization`命名空间中的`XmlSerializer`类实现。
2.1 基本实现
using System;
using System.IO;
using System.Xml.Serialization;
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
}
public class XmlSerializationDemo
{
public static void Serialize()
{
var book = new Book { Title = "C#高级编程", Author = "Jon Skeet", Price = 99.99m };
var serializer = new XmlSerializer(typeof(Book));
using (var writer = new StreamWriter("book.xml"))
{
serializer.Serialize(writer, book);
}
Console.WriteLine("XML序列化完成");
}
public static void Deserialize()
{
var serializer = new XmlSerializer(typeof(Book));
using (var reader = new StreamReader("book.xml"))
{
var book = (Book)serializer.Deserialize(reader);
Console.WriteLine($"反序列化结果: Title={book.Title}, Price={book.Price}");
}
}
}
生成的XML文件内容:
C#高级编程
Jon Skeet
99.99
2.2 高级特性
控制XML元素名称:
[XmlRoot("LibraryBook")]
public class Book
{
[XmlElement("BookTitle")]
public string Title { get; set; }
[XmlAttribute("authorName")]
public string Author { get; set; }
}
忽略字段:
public class Book
{
public string Title { get; set; }
[XmlIgnore]
public string InternalCode { get; set; } // 不会被序列化
}
2.3 优缺点分析
优点:
- 人类可读,便于调试
- 支持跨平台和多种编程语言
- 可通过XSD验证数据结构
缺点:
- 序列化结果体积较大
- 性能低于二进制序列化
- 不支持循环引用
三、JSON序列化
JSON(JavaScript Object Notation)已成为Web API和现代应用的首选数据格式。.NET通过`System.Text.Json`(.NET Core 3.0+)和`Newtonsoft.Json`(第三方库)提供JSON序列化支持。
3.1 System.Text.Json实现
微软官方推荐的轻量级JSON库,性能优于Newtonsoft.Json:
using System;
using System.IO;
using System.Text.Json;
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public decimal UnitPrice { get; set; }
}
public class JsonSerializationDemo
{
public static void Serialize()
{
var product = new Product
{
Id = "P001",
Name = "笔记本电脑",
UnitPrice = 5999.99m
};
var options = new JsonSerializerOptions
{
WriteIndented = true, // 格式化输出
PropertyNamingPolicy = JsonNamingPolicy.CamelCase // 属性名转为驼峰式
};
var json = JsonSerializer.Serialize(product, options);
File.WriteAllText("product.json", json);
Console.WriteLine("JSON序列化完成");
}
public static void Deserialize()
{
var json = File.ReadAllText("product.json");
var product = JsonSerializer.Deserialize(json);
Console.WriteLine($"反序列化结果: Name={product.Name}, Price={product.UnitPrice}");
}
}
生成的JSON文件内容:
{
"id": "P001",
"name": "笔记本电脑",
"unitPrice": 5999.99
}
3.2 Newtonsoft.Json实现
虽然微软推荐使用System.Text.Json,但Newtonsoft.Json仍因其丰富的功能被广泛使用:
using System;
using System.IO;
using Newtonsoft.Json;
public class Order
{
public string OrderId { get; set; }
public DateTime OrderDate { get; set; }
[JsonProperty("customer_name")] // 自定义属性名
public string CustomerName { get; set; }
}
public class NewtonsoftJsonDemo
{
public static void Serialize()
{
var order = new Order
{
OrderId = "ORD1001",
OrderDate = DateTime.Now,
CustomerName = "张三"
};
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatString = "yyyy-MM-dd" // 自定义日期格式
};
var json = JsonConvert.SerializeObject(order, settings);
File.WriteAllText("order.json", json);
}
public static void Deserialize()
{
var json = File.ReadAllText("order.json");
var order = JsonConvert.DeserializeObject(json);
Console.WriteLine($"反序列化结果: OrderId={order.OrderId}, Date={order.OrderDate}");
}
}
3.3 性能对比与选择建议
特性 | System.Text.Json | Newtonsoft.Json |
---|---|---|
性能 | 更快(原生实现) | 较慢 |
功能 | 基础功能 | 更丰富(如LINQ to JSON) |
跨平台 | 完全支持 | 完全支持 |
推荐场景 | 新项目、高性能需求 | 遗留系统、复杂JSON处理 |
四、三种序列化方法对比
对比项 | 二进制序列化 | XML序列化 | JSON序列化 |
---|---|---|---|
可读性 | 不可读 | 人类可读 | 人类可读 |
性能 | 最快 | 最慢 | 中等 |
体积 | 最小 | 最大 | 中等 |
跨平台 | 差(已不推荐) | 好 | 最好 |
典型应用 | 进程间通信、缓存 | 配置文件、Web服务 | Web API、移动应用 |
五、最佳实践建议
1. 安全性优先:避免使用`BinaryFormatter`,优先选择JSON或安全二进制方案
2. 性能敏感场景:.NET Core 3.1+使用`System.Text.Json`,遗留系统可考虑`Newtonsoft.Json`
3. 跨平台需求:优先选择JSON或XML
4. 版本控制:为序列化类添加版本控制特性(如`[ProtoContract]`用于Protocol Buffers)
5. 敏感数据:序列化前加密敏感字段,反序列化后解密
六、完整示例:综合应用
using System;
using System.IO;
using System.Text.Json;
using System.Xml.Serialization;
// 共享模型
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class SerializationComparison
{
public static void RunAll()
{
var customer = new Customer
{
Id = 1001,
Name = "李四",
Email = "lisi@example.com"
};
// JSON序列化
JsonSerialize(customer);
// XML序列化
XmlSerialize(customer);
// 安全二进制模拟(实际应避免BinaryFormatter)
SafeBinarySimulation(customer);
}
private static void JsonSerialize(Customer customer)
{
var options = new JsonSerializerOptions { WriteIndented = true };
var json = JsonSerializer.Serialize(customer, options);
File.WriteAllText("customer.json", json);
Console.WriteLine("JSON序列化结果已保存");
}
private static void XmlSerialize(Customer customer)
{
var serializer = new XmlSerializer(typeof(Customer));
using (var writer = new StreamWriter("customer.xml"))
{
serializer.Serialize(writer, customer);
}
Console.WriteLine("XML序列化结果已保存");
}
private static void SafeBinarySimulation(Customer customer)
{
// 实际开发中应使用更安全的方案
var json = JsonSerializer.Serialize(customer);
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
File.WriteAllBytes("customer_simulated_bin.dat", bytes);
Console.WriteLine("模拟安全二进制序列化完成");
}
}
// 程序入口
class Program
{
static void Main()
{
SerializationComparison.RunAll();
Console.WriteLine("所有序列化操作完成");
}
}
关键词:C#序列化、二进制序列化、XML序列化、JSON序列化、System.Text.Json、Newtonsoft.Json、.NET序列化、对象持久化、数据交换格式
简介:本文详细介绍了C# (.NET)中的三种主流序列化方法:二进制序列化、XML序列化和JSON序列化。通过完整的代码示例展示了每种方法的实现方式,分析了它们的性能、可读性、安全性等特点,并提供了跨平台兼容性和最佳实践建议。适合需要处理数据持久化、网络通信或缓存存储的C#开发者参考。