Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Serialization และ Deserialization ใน C#

Serialization = แปลง Object → Byte Stream (เพื่อบันทึก File, Database, ส่ง Network)
Deserialization = แปลง Byte Stream → Object (กลับมาใช้งาน)

ประเภทหลักใน .NET

1. Binary Serialization (Legacy — ไม่แนะนำ)

  • Serialize ทุก Field (รวม private, readonly)
  • Binary Format — ไม่ Human-readable
  • Versioning ยาก, Security Risk (Type Confusion)
  • Obsolete ใน .NET 5+ — ใช้ System.Text.Json หรือ XmlSerializer แทน

2. XML Serialization

  • Serialize Public Properties/Fields เท่านั้น
  • Human-readable, Interoperable
  • ต้องมี Parameterless Constructor
  • ใช้ XmlSerializer

3. JSON Serialization (Modern Standard)

  • System.Text.Json (Built-in .NET Core 3.0+ / .NET 5+) — เร็ว, Low Allocation
  • Newtonsoft.Json (Json.NET) — Feature-rich, ยังนิยมใช้

ตัวอย่าง: System.Text.Json (แนะนำ)

using System;
using System.Text.Json;
using System.IO;

public class Employee {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public DateTime HireDate { get; set; }
    // Private field ไม่ serialize (default)
    private string _ssn;
}

class Program {
    static void Main() {
        var emp = new Employee {
            Id = 30,
            Name = "Tom",
            Department = "Operations",
            HireDate = new DateTime(2020, 1, 15)
        };
        
        // Serialize to JSON String
        string json = JsonSerializer.Serialize(emp, new JsonSerializerOptions { 
            WriteIndented = true 
        });
        Console.WriteLine("JSON:");
        Console.WriteLine(json);
        
        // Write to File
        File.WriteAllText("employee.json", json);
        
        // Deserialize from String
        Employee emp2 = JsonSerializer.Deserialize(json);
        Console.WriteLine($"\nDeserialized: {emp2.Name}, {emp2.Department}");
        
        // Deserialize from File
        string jsonFromFile = File.ReadAllText("employee.json");
        Employee emp3 = JsonSerializer.Deserialize(jsonFromFile);
        
        Console.ReadKey();
    }
}

ตัวอย่าง: XML Serialization

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; }
    
    [XmlIgnore] // ไม่ Serialize Field นี้
    public string SSN { get; set; }
}

class Program {
    static void Main() {
        var emp = new EmployeeXml { Id = 30, Name = "Tom", SSN = "123-45-6789" };
        
        var serializer = new XmlSerializer(typeof(EmployeeXml));
        
        // Serialize
        using (var writer = new StreamWriter("employee.xml")) {
            serializer.Serialize(writer, emp);
        }
        
        // Deserialize
        EmployeeXml emp2;
        using (var reader = new StreamReader("employee.xml")) {
            emp2 = (EmployeeXml)serializer.Deserialize(reader);
        }
        
        Console.WriteLine(emp2.Name); // Tom
        Console.ReadKey();
    }
}

ตัวอย่าง: BinaryFormatter (Legacy — เรียนรู้อย่างเดียว)

// ⚠️ OBSOLETE - Security Risk, Versioning Issues
// [Serializable] attribute required
[Serializable]
class EmployeeBinary {
    public int Id;
    public string Name;
    public string Department;
}

// Usage (Not recommended for new code)
/*
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream fs = new FileStream("emp.bin", FileMode.Create)) {
    formatter.Serialize(fs, emp);
}
using (FileStream fs = new FileStream("emp.bin", FileMode.Open)) {
    EmployeeBinary emp2 = (EmployeeBinary)formatter.Deserialize(fs);
}
*/

Comparison

FeatureSystem.Text.JsonNewtonsoft.JsonXmlSerializerBinaryFormatter
Performance⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Human Readable✅✅✅❌
Private Members❌ (Default)✅ (Config)❌✅
Version Tolerance✅ Good✅ Excellent⚠️ Limited❌ Poor
Security✅ Safe⚠️ Config Needed✅ Safe❌ Unsafe
.NET VersionCore 3.0+AllFrameworkLegacy Only

สรุป

  • New Projects: ใช้ System.Text.Json (Built-in, Fast, Secure)
  • Complex Scenarios: Newtonsoft.Json (Polymorphism, Custom Converters, JSON Schema)
  • Interop/Legacy: XmlSerializer
  • หลีกเลี่ยง: BinaryFormatter (Security Vulnerability, Obsolete)