[c#] C# 직렬화와 데이터 교환 형식

C#에서 직렬화(serialization)는 객체를 데이터 스트림이나 바이트 배열로 변환하는 과정을 뜻합니다. 직렬화된 데이터는 저장, 전송, 또는 다른 시스템간 데이터 교환을 위해 사용됩니다. C#에서는 XML, JSON, 바이너리 형식 등 다양한 형식으로 데이터를 직렬화할 수 있습니다.

XML 직렬화

XML 직렬화는 .NET Framework에서 제공하는 기본적인 형식 중 하나입니다. System.Xml.Serialization 네임스페이스를 사용하여 객체를 XML 형식으로 직렬화할 수 있습니다. 아래는 XML 직렬화의 간단한 예시입니다.

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

public class Example
{
    public static void Main()
    {
        // 직렬화
        XmlSerializer serializer = new XmlSerializer(typeof(Example));
        using (TextWriter writer = new StreamWriter("example.xml"))
        {
            serializer.Serialize(writer, new Example());
        }

        // 역직렬화
        using (TextReader reader = new StreamReader("example.xml"))
        {
            Example deserialized = (Example)serializer.Deserialize(reader);
        }
    }
}

JSON 직렬화

JSON 직렬화는 XML 대신 JSON 형식으로 객체를 직렬화하는 방법입니다. 이를 위해 System.Text.Json 또는 Newtonsoft.Json 라이브러리를 사용할 수 있습니다. 아래는 System.Text.Json을 사용한 JSON 직렬화 예시입니다.

using System;
using System.Text.Json;

public class Example
{
    public static void Main()
    {
        Example example = new Example();
        string jsonString = JsonSerializer.Serialize(example);

        Example deserialized = JsonSerializer.Deserialize<Example>(jsonString);
    }
}

바이너리 직렬화

바이너리 직렬화는 데이터를 바이너리 형태로 직렬화하는 방법으로, 효율적인 저장과 전송을 위해 사용됩니다. System.Runtime.Serialization.Formatters.Binary를 사용하여 객체를 바이너리 형식으로 직렬화할 수 있습니다. 아래는 바이너리 직렬화의 간단한 예시입니다.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class Example
{
    public static void Main()
    {
        // 직렬화
        BinaryFormatter formatter = new BinaryFormatter();
        using (Stream stream = new FileStream("example.bin", FileMode.Create, FileAccess.Write, FileShare.None))
        {
            formatter.Serialize(stream, new Example());
        }

        // 역직렬화
        using (Stream stream = new FileStream("example.bin", FileMode.Open))
        {
            Example deserialized = (Example)formatter.Deserialize(stream);
        }
    }
}

C#에서는 다양한 직렬화 방식을 활용하여 데이터를 교환하고 저장할 수 있습니다. 개발하고 있는 애플리케이션의 요구사항에 맞춰 적절한 직렬화 방식을 선택하는 것이 중요합니다.

참고 자료