분류 전체보기 (328)
.NET (111)
S/W tip (35)
etc (63)
DB (34)
HOT item~! (48)
Disign pettens (4)
UX (6)
나의 S/W (2)
개발관련 이슈 (16)
Diary (1)
웹플러스 (1)
calendar
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
tags
archive
link
ColorSwitch 00 01 02

http://blog.naver.com/dolmoon/60051473626
 

객체 직렬화와 관련된 일반적인 사항들은 다음 사이트를 참고한다.

http://en.wikipedia.org/wiki/Serialization

http://msdn.microsoft.com/ko-kr/library/system.serializableattribute.aspx



Serialization(직렬화) : WikiPedia에 나와 있는 정의를 대충(?) 요약하면 다음과 같다.

In computer science, in the context of data storage and transmission, serialization is the process of saving an object onto a storage medium (such as a file, or a memory buffer) or to transmit it across a network connection link in binary form. The series of bytes or the format can be used to re-create an object that is identical in its internal state to the original object (actually, a clone).

This process of serializing an object is also called deflating or marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is also called inflating or unmarshalling).

직렬화는 객체를 저장매체(파일이나 메모리와 같은)에 저장하거나 바이너리(이진) 형태로 네트워크를 통해 전달하기 위해 저장하는 과정이다. 이(객체를 직렬화한) 연속된 바이트나 포맷은 다시 원래 객체가 가지고 있던 상태로 객체를 재생성하는데 사용할 수 있다. 이렇게 객체를 직렬화하는 과정은 디플레이팅(deflating) 또는 마샬링(marshalling)이라고도 부른다. 직렬화와는 반대로 연속된 바이트로부터 어떤 데이터 구조를 추출해내는 과정을 역직렬화(deserialization)라고 한다. 역직렬화는 인플레이팅(inflating) 또는 언마샬링(unmarshalling)이라 불리기도 한다.

 

간단한 직렬화 예제

C#에서 객체 직렬화가 가능한 클래스를 만들기 위해서는 다음 한 가지만 처리하면 된다.

  • SerializableAttribute 특성을 클래스에 적용한다.

다음은 클래스에 SerializableAttribute 특성을 적용하여 직렬화하고 역 직렬화하는 예제이다.

using System;
using System.Runtime.Serialization.Formatters.Soap; //SOAP Formatter를 이용하여 직렬화, 역직렬화할 경우에 사용한다.
//using System.Runtime.Serialization.Formatters.Binary; //Binary Formatter를 이용하여 직렬화, 역직렬화할 경우에 사용한다.
using System.IO;


namespace Infodigm
{
    [Serializable()]   //클래스에 SerializableAttribute 특성을 적용하여 직렬화 가능한 클래스로 지정한다.
    class SerializablePeople
    {
        private string _name;

        private readonly string _socialSecurityNumber;


        public string Name //public 멤버는 직렬화에 포함된다.
        {
            get { return _name; }
            set { _name = value; }
        }


        public string SocialSecurityNumber
        {
            get { return _socialSecurityNumber; }
        }


        public SerializablePeople(string name, string socialSecurityNo)
        {
            _name = name;
            _socialSecurityNumber = socialSecurityNo;
        }


        public override string ToString()
        {
            return "Name = " + _name + ", SocialSecurityNo = " + _socialSecurityNumber;
        }
    }


    static class Program
    {
        static void Main(string[] args)
        {

            //클래스 오브젝트 생성
            SerializablePeople people = new SerializablePeople("홍길동", "111111-1111111");
            Console.WriteLine("원본 : " + people.ToString());

            //직렬화해서 저장할 파일스트림을 연다.
            Stream stream = File.Open("data.xml", FileMode.Create);

            //SOAP Formatter 개체를 만든다.
            SoapFormatter soapFormatter = new SoapFormatter();
            //BinaryFormatter binaryFormatter = new BinaryFormatter();

            //오브젝트를 SOAP Formatter로 직렬화하여 파일스트림으로 내보낸다.
            soapFormatter.Serialize(stream, people);
            //binaryFormatter.Serialize(stream, people);

            //파일 스트림을 닫는다.
            stream.Close();

            people.Name = "DESERIALIZED";
            Console.WriteLine("직렬화 후 원본변경 : " + people.ToString());
            people = null;

            //직렬화된 파일을 연다.

            stream = File.Open("data.xml", FileMode.Open);

            //파일로부터 역직렬화하여 원래 오브젝트로 캐스팅한다.
            SerializablePeople deSerializedPeople = (SerializablePeople)soapFormatter.Deserialize(stream);
            //SerializablePeople deSerializedPeople = (SerializablePeople)binaryFormatter.Deserialize(stream);
            stream.Close();
            Console.WriteLine("직렬화된 데이터 복원 : " + deSerializedPeople.ToString());

            Console.ReadLine();
        }
    }
}


※ SoapFormatter를 사용했을 때 주의할 점은 .NET Framework 버전의 호환이 되지않는다는 점이다.

이점과 관련해서는 MSDN에 다음과 같이 설명되어 있다

  • SoapFormatter는 .NET Framework 버전 간의 serialization 호환성을 지원하지 않습니다. 따라서 Framework 버전 1.1 형식과 2.0 형식 간의 serialization은 실패할 수 있습니다. 이 문제를 해결하려면 다음을 수행합니다.

articles
recent replies
recent trackbacks
notice
Admin : New post