Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Serialization (Tuần tự hóa) trong C#.NET

Serialization là quá trình chuyển đổi đối tượng thành luồng byte (byte stream) để lưu trữ (file, DB, memory) hoặc truyền qua mạng. Quá trình ngược là Deserialization.

3 loại chính trong .NET

LoạiNamespaceĐặc điểmDùng cho
Binary Serialization System.Runtime.Serialization.Formatters.Binary Toàn bộ object graph (private/public), compact, binary, không readable. Deprecated (bảo mật). Legacy .NET Framework, remoting
XML Serialization System.Xml.Serialization Chỉ public properties/fields, readable, interoperable, chậm hơn, kích thước lớn. Config, web services (ASMX), interop
JSON Serialization (Hiện đại) System.Text.Json (.NET Core 3+), Newtonsoft.Json Nhanh, compact, chuẩn web, hỗ trợ polymorphic, nullable, source gen. Mặc định cho mọi app mới (Web API, config, log, cache)

Ví dụ: System.Text.Json (Khuyên dùng)

using System;
using System.Text.Json;

public record Employee(int Id, string Name, string Department);

class Program
{
    static void Main()
    {
        var emp = new Employee(30, "Tom", "Operations");
        
        // Serialize
        string json = JsonSerializer.Serialize(emp, new JsonSerializerOptions 
        { 
            WriteIndented = true,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        });
        Console.WriteLine("JSON:");
        Console.WriteLine(json);
        
        // Deserialize
        var emp2 = JsonSerializer.Deserialize<Employee>(json);
        Console.WriteLine($"\nDeserialized: {emp2}");
    }
}

Kết quả

JSON:
{
  "id": 30,
  "name": "Tom",
  "department": "Operations"
}

Deserialized: Employee { Id = 30, Name = Tom, Department = Operations }

Ví dụ: XML Serialization (Legacy/Interop)

using System;
using System.Xml.Serialization;
using System.IO;

[XmlRoot("Employee")]
public class EmployeeXml
{
    [XmlElement("Id")]
    public int Id { get; set; }
    
    [XmlElement("Name")]
    public string Name { get; set; }
    
    [XmlElement("Dept")]
    public string Department { get; set; }
}

class Program
{
    static void Main()
    {
        var emp = new EmployeeXml { Id = 30, Name = "Tom", Department = "Operations" };
        
        var serializer = new XmlSerializer(typeof(EmployeeXml));
        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, emp);
            Console.WriteLine(writer.ToString());
        }
    }
}

Binary Serialization (Deprecated - Không dùng cho code mới)

// CHỈ DÙNG CHO LEGACY MAINTENANCE
// [Serializable] attribute bắt buộc
[Serializable]
public class EmployeeBin
{
    public int Id;
    public string Name;
    public string Department;
}

// BinaryFormatter bị obsolete, không an toàn (deserialization attack)

Best Practices

  1. Mặc định dùng System.Text.Json (built-in, nhanh, an toàn).
  2. Dùng record (C# 9+) cho DTO immutable, tự động generate ToString/Equality.
  3. Cấu hình JsonSerializerOptions: PropertyNamingPolicy, DefaultIgnoreCondition, Converters.
  4. Tránh BinaryFormatter (cảnh báo bảo mật critical).
  5. Dùng [JsonIgnore], [JsonPropertyName] để kiểm soát serialization.