(Microsoft PowerPoint - hci2-lecture12 [\310\243\310\257 \270\360\265\345])

Similar documents
Microsoft PowerPoint - hci2-lecture12 [호환 모드]

PowerPoint Presentation

PowerPoint Presentation

gnu-lee-oop-kor-lec06-3-chap7

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

PowerPoint Presentation

JAVA PROGRAMMING 실습 08.다형성

JAVA PROGRAMMING 실습 05. 객체의 활용

(Microsoft PowerPoint - C#\260\355\261\3361.ppt)

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - CSharp-10-예외처리

3ÆÄÆ®-14

PowerPoint 프레젠테이션

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

Design Issues

PowerPoint Presentation

JAVA PROGRAMMING 실습 05. 객체의 활용

어댑터뷰

PowerPoint Presentation

비긴쿡-자바 00앞부속

PowerPoint Presentation

예제 2) Test.java class A intvar= 10; void method() class B extends A intvar= 20; 1"); void method() 2"); void method1() public class Test 3"); args) A

JAVA PROGRAMMING 실습 02. 표준 입출력

(8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI= ; // PI 이름으로 로초기화된정적상수 public

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍

@OneToOne(cascade = = "addr_id") private Addr addr; public Emp(String ename, Addr addr) { this.ename = ename; this.a

쉽게 풀어쓴 C 프로그래밍

Microsoft PowerPoint - 04-UDP Programming.ppt

PowerPoint 프레젠테이션

Microsoft PowerPoint - C++ 5 .pptx

PowerPoint Presentation

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345])

Microsoft PowerPoint - Lect04.pptx

<4D F736F F D20BEBEBCA520C4DAB5F920BFACBDC0202D20B8D6C6BC20BEB2B7B9B5E5BFCD20C0CCBAA5C6AE2E646F6378>

<4D F736F F F696E74202D20C1A63234C0E520C0D4C3E2B7C228B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

JAVA PROGRAMMING 실습 07. 상속

Microsoft PowerPoint - 2강

1. 객체의생성과대입 int 형변수 : 선언과동시에초기화하는방법 (C++) int a = 3; int a(3); // 기본타입역시클래스와같이처리가능 객체의생성 ( 복습 ) class CPoint private : int x, y; public : CPoint(int a

C++ Programming

PowerPoint Presentation

Microsoft PowerPoint - Chapter 6.ppt

17장 클래스와 메소드

rmi_박준용_final.PDF

쉽게 풀어쓴 C 프로그래밍

5장.key

PowerPoint 프레젠테이션

JVM 메모리구조

Spring Data JPA Many To Many 양방향 관계 예제

제11장 프로세스와 쓰레드

교육자료

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

설계란 무엇인가?

Microsoft PowerPoint - additional08.ppt [호환 모드]

PowerPoint Presentation

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밍

Network Programming

Microsoft PowerPoint - Chap12-OOP.ppt

C++ Programming

PowerPoint 프레젠테이션

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

(Microsoft PowerPoint - 07\300\345.ppt [\310\243\310\257 \270\360\265\345])

쉽게 풀어쓴 C 프로그래밊

PowerPoint Presentation

JAVA PROGRAMMING 실습 09. 예외처리

PowerPoint 프레젠테이션

05-class.key

Interstage5 SOAP서비스 설정 가이드

PowerPoint 프레젠테이션

제8장 자바 GUI 프로그래밍 II

3ÆÄÆ®-11

슬라이드 1

Microsoft PowerPoint - additional06.ppt [호환 모드]

슬라이드 1

PowerPoint 프레젠테이션

Microsoft PowerPoint - Java7.pptx

(Microsoft PowerPoint - java2-lecture3.ppt [\310\243\310\257 \270\360\265\345])

안드로이드기본 11 차시어댑터뷰 1 학습목표 어댑터뷰가무엇인지알수있다. 리스트뷰와스피너를사용하여데이터를출력할수있다. 2 확인해볼까? 3 어댑터뷰 1) 학습하기 어댑터뷰 - 1 -

No Slide Title

Microsoft PowerPoint 장강의노트.ppt

C++ Programming

1. auto_ptr 다음프로그램의문제점은무엇인가? void func(void) int *p = new int; cout << " 양수입력 : "; cin >> *p; if (*p <= 0) cout << " 양수를입력해야합니다 " << endl; return; 동적할

Microsoft Word - EEL2 Lab4.docx

PowerPoint 프레젠테이션

Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

Microsoft Word - java19-1-midterm-answer.doc

I T C o t e n s P r o v i d e r h t t p : / / w w w. h a n b i t b o o k. c o. k r

(Microsoft Word - C# \304\332\265\371 \277\254\275\300.docx)

슬라이드 1

12-file.key

C++ Programming

PowerPoint Presentation

유니티 변수-함수.key

<4D F736F F F696E74202D2036C0CFC2B05FB0B4C3BCC1F6C7E2C7C1B7CEB1D7B7A1B9D62E707074>

자바 프로그래밍

임베디드시스템설계강의자료 6 system call 2/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과

슬라이드 1

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Spring Boot/JDBC JdbcTemplate/CRUD 예제

Transcription:

Serialization C# Serialization 321190 2015 년가을학기 11/27/2015 박경신 Serializaiton( 직렬화 ) 란객체상태를지속시키거나전송할수있는형식으로변환하는과정으로, Serialization 반대로다시객체로변환하는것을 Deserialization 임 Serialization 을사용하는이유 객체의상태를저장소에보존했다가나중에똑같은복사본을다시만들기위하거나, 한응용프로그램에서다른응용프로그램으로객체를전송하기위해서임 닷넷에서제공하는 Serialization 방식 Binary Serialization 형식 (Type) 정확도를유지하므로응용프로그램의여러호출간에객체상태를유지하는데유용. 객체를스트림, 디스크, 메모리, 네트워크등으로 serialize 함. XML Serialization public 속성과필드만 serialize 하며형식정확도를유지하지않음. XML 은공개표준이므로웹을통해데이터를공유하는데효과적인방법임. Serialization Binary Serialization Serialize 하고자하는객체의 public, private 필드와클래스이름을모두바이트의스트림 (binary) 로변환하는방식이며, deserialize 되면원본객체의정확한복제본이생성 Binary Serialization 방법 기본 Serialization 클래스의일부멤버를 Serialize 하는선택적 Serialization ISerializable 인터페이스를사용한사용자지정 Serialization XML/SOAP Serialization XML Serialization 은객체의 public 필드와속성또는메소드의매개변수와반환값을 XML 스트림으로 Serialize 하는방식으로, XML Serialization 을사용하면저장이나전송을위해직렬형식으로변환되는 public 속성및필드가있는강력한형식클래스생성 XML/SOAP Serialization 방법 XML Serialization SOAP 인코딩된 XML 스트림으로 Serialization 기본 Serialization 클래스를 Serializable 특성으로표시 public class MyObject { public int n1 = 0; public int n2 = 0; public string str = null; 클래스객체를 Serialize 하여파일로저장 MyObject obj = new MyObject(); // 객체생성 obj.n1 = 1; obj.n2 = 2; obj.str = test ; FileStream stream = new FileStream( TestFile.bin, FileMode.Create, FileAccess.Write, FileShare.None); // FileStream 생성 BinaryFormatter bf= new BinaryFormatter(); // BinaryFormatter 생성 bf.serialze(stream, obj); // Formatter에게 stream과객체를주고 serialize stream.close(); // FileStream 닫기 Serialize 된객체를반대로 Deserialize 로복원 BinaryFormatter bf= new BinaryFormatter(); // BinaryFormatter 생성 FileStream stream = new FileStream( TestFile.bin, FileMode.Open, FileAccess.Read); MyObject obj = (MyObject) bf.deserialze(stream); // Deserialize stream.close(); // FileStream 닫기

get { return name; set { name = value; LPersonBinaryFormatter, Version=1.0.0.0, Culture=neutral, PublicKeyToken =null Person BinaryFormatter.Person nameidphone address 뺢꼍? 졆 041-550-3469 3?17 using System.Runtime.Serialization.Formatters.Binary; FileStream fs = new FileStream(@ C:\Person.bin, FileMode.Create, BinaryFormatter bf= new BinaryFormatter(); bf.serialze(fs, p); // Formatter 에게 stream 과 Person 객체를주고 serialize get { return name; set { name = value; using System.Runtime.Serialization.Formatters.Soap; FileStream fs = new FileStream(@ C:\Person.xml, FileMode.Create, SoapFormatter sf= new SoapFormatter(); sf.serialze(fs, p); // SoapFormatter 에게 stream 과 Person 객체를주고 serialize <SOAP-ENV:Envelope xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:soap- ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap- ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0 " SOAP- ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encodin g/"> <SOAP-ENV:Body> <a1:person id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/personso apformatter/personsoapformatter%2c%20version%3d1.0.0.0% 2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"> <name id="ref-3"> 박경신 </name> <id>1207</id> <phone id="ref-4">041-550-3469</phone> <address id="ref-5">3 과 417</address> </a1:person> </SOAP-ENV:Body> </SOAP-ENV:Envelope> using System.Runtime.Serialization.Formatters.Binary; List<Person> plist = new List<Person>(); FileStream fs = new FileStream(@ C:\PersonList.bin, FileMode.Create, BinaryFormatter bf= new BinaryFormatter(); bf.serialze(fs, plist); // BinaryFormatter 에게 stream 과 Person 리스트객체를주고 serialize private void button2_click(object sender, EventArgs e) { FileStream fs = new FileStream(@ C:\PersonList.bin, FileMode.Open, FileAccess.Read); BinaryFormatter bf= new BinaryFormatter(); plist = (List<Person>)bf.Deserialze(fs); // Person 리스트 deserialize // 리스트뷰에출력 listview1.items.clear(); foreach (Person p in plist) { listview1.items.add(p.tolistviewitem());

PPersonListBinaryFormatter, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null?System.Collections.Generic.List`1[[ PersonListBinaryFormatter.Person, PersonListBinaryFormatter, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _items_size_version "PersonListBinaryFormatter.Person[] PersonListBinaryFormatter.Person PersonListBinaryFormatter.Person nameidphone address 뺢꼍? 졆 041-550-3469 3?17 고씎 041-550-3490 2?15 뺤젙? 쑔 041-550-3490 2?15 선택적 Serialization 클래스에서 serialize 하지않아야할필드를 NonSerialized 특성으로표시함으로써해당변수가 Serialize 되지않게함 public class MyObject { public int n1 = 0; [NonSerialized] public int n2 = 0; // n2 멤버는더이상 serialize 되지않음 public string str = null; <SOAP-ENV:Envelope xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:soap- ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap- ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0 " SOAP- ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encodin g/"> <SOAP-ENV:Body> <a1:person id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/personso apformatter/personsoapformatter%2c%20version%3d1.0.0.0% 2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"> <name id="ref-3"> 박경신 </name> <phone id="ref-4">041-550-3469</phone> <address id="ref-5">3 과 417</address> </a1:person> </SOAP-ENV:Body> </SOAP-ENV:Envelope> public class Person { [NonSerialized] // 중간생략 Custom Serialization ISerializable 인터페이스를사용한사용자지정 Serialization // GetObjectData 메소드와 deserialize 될때사용되는특수생성자구현이포함되어야함 public class MyObject : ISerializable { public int n1=0; public int n2=0; public string str=null; public MyObject() { protected MyObject(SerializationInfo info, StreamingContext context) { n1 = info.getint32( i ); n2 = info.getint32( j ); str = info.getstring( k ); // deserialize 시필요 [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public virtual void GetObjectData(SerializationInfo info, StreamingContext context){ info.addvalue( i, n1); info.addvalue( j, n2); info.addvalue( k, str); // serialize 시필요

public class Person: IComparable<Person>, IEquatable<Person>, ISerializable { <?xml version="1.0"?> <Person xmlns:xsi="http://www.w3.org xmlns:xsd="http://www.w3.org/2001/x <Name> 박경신 </Name> <ID>1207</ID> <Phone>041-550-3469</Phone> <Address>3 과 417</Address> #region ISerializable public Person(SerializationInfo info, StreamingContext context) { this.name = info.getstring("name"); this.id = info.getint32("id"); this.phone = info.getstring("phone"); this.address = info.getstring("address"); public void GetObjectData(SerializationInfo info, StreamingContext context) { info.addvalue("name", this.name); info.addvalue("id", this.id); info.addvalue("phone", this.phone); info.addvalue("address", this.address); #endregion Custom Serialization 사용자가 Serialization 을직접제어하는방식으로 ISerializable 인터페이스를사용하는방식외에, Serialization 도중과이후에데이터를수정하는데사용되는메소드에다음특성을적용 OnDeserializedAttribute OnDeserializing Attribute OnSerializedAttribute OnSerializingAttribute XML Serialization XML Serialization 특징 XML 은공개표준이기때문에 XML 스트림은플랫폼에관계없이필요에따라모든응용프로그램에서처리될수있음 XML serialization 은 SOAP 사양과일치하는 XML 스트림으로객체를 serialize 하는데사용할수있음 객체를 serialize 하거나 deserialize 하기위해서는 XmlSerializer 클래스를사용 Serialize 된데이터에는데이터자체와클래스의구조만포함 Public 속성및필드만 serialize 될수있음 만약 public 이아닌데이터를 serialize 해야하는경우 binary serialization 을사용할것 클래스는 XmlSerializer 에의해 serialize 될기본생성자가있어야함 메소드는 serialize 될수없음 XML Serialization XmlSerializer 를사용하여 serialize/deserialize 하는방법 public class MyObject { public int n1=0; private int n2=0; public string str=null; public MyObject() { n1 = 1; n2 =2; str= XML serialization ; // 결과물인 obj.xml 에는 private 멤버와메소드의정보는기록되지않음 class Program { static void Main(string[] args) { MyObject obj = new MyObject(); // MyObject 객체생성 // XmlSerializer 생성자에 serialize 하고자하는객체의타입을전달하여생성 XmlSerializer xs = new XmlSerializer(typeof(MyObject)); StreamWriter sw = new StreamWriter( obj.xml ); // stream writer 생성 xs.serialize(sw, obj); // XmlSerializer 에게 stream 과객체를전달하여 serialize sw.close(); StreamReader sr = new StreamReader( obj.xml ); // stream reader 생성 MyObject obj2 = (MyObject) xs.deserialize(sr); // deserialize Console.WriteLine( n1= + obj2.n1 + str= + obj2.str); sr.close();

SOAP 인코딩된 XML Serialization SOAP 인코딩된 XML Serialize 하기위해서는, 새로운 SoapReflectionImporter 를만들고 serialize 된클래스의형식으로 ImportTypeMapping 메소드를호출하여 XmlTypeMapping 을만든뒤 XmlSerializer 생성자매개변수에전달 class Program { static void Main(string[] args) { MyObject obj = new MyObject(); // MyObject 객체생성 XmlTypeMapping xtm = new SoapReflectionImporter().ImportTypeMapping(typeof(MyObject)); XmlSerializer xs = new XmlSerializer(xtm); StreamWriter sw = new StreamWriter( obj.xml ); // stream writer 생성 xs.serialize(sw, obj); // XmlSerializer에게 stream과객체를전달하여 serialize sw.close(); [XmlAttribute(AttributeName= Name )] get { return name; set { name = value; FileStream fs = new FileStream(@ C:\Person.xml, FileMode.Create, XmlSerializer xs= new XmlSerializer(typeof(Person)); xs.serialze(fs, p); // XmlSerializer 에게 stream 과 Person 객체를주고 serialize [XmlAttribute(AttributeName= Name )] get { return name; set { name = value; FileStream fs = new FileStream(@ C:\Person.xml, FileMode.Create, XmlTypeMapping xtm= new SoapReflectionImporter().ImportTypeMapping(typeof(Person)); XmlSerializer xs= new XmlSerializer(xtm); xs.serialze(fs, p); // XmlSerializer에게 stream과 Person 객체를주고 serialize [XmlAttribute(AttributeName= Name )] get { return name; set { name = value; FileStream fs = new FileStream(@ C:\PersonList.xml, FileMode.Create, XmlSerializer xs= new XmlSerializer(typeof(List<Person>)); xs.serialze(fs, plist); // XmlSerializer 에게 stream 과 Person 리스트객체를주고 serialize

<?xml version="1.0"?> - <ArrayOfPerson xmlns:xsd="http://www.w3.org/2001/xmlschema"> <Person Name=" 박경신 " ID="1207" Phone="041-550-3469" Address="3과417" /> <Person Name=" 조흥목 " ID="1204" Phone="041-550-3490" Address="2과315" /> <Person Name=" 박정서 " ID="1203" Phone="041-550-3490" Address="2과315" /> </ArrayOfPerson> [XmlElement( Name )] get { return name; set { name = value; FileStream fs = new FileStream(@ C:\PersonList2.xml, FileMode.Create, XmlSerializer xs= new XmlSerializer(typeof(List<Person>)); xs.serialze(fs, plist); // XmlSerializer 에게 stream 과 Person 리스트객체를주고 serialize <?xml version="1.0"?> - <ArrayOfPerson xmlns:xsd="http://www.w3.org/2001/xmlschema"> - <Person> <Name xmlns="urn:person"> 박경신 </Name> <ID xmlns="urn:person">1207</id> <Phone xmlns="urn:person">041-550-3469</phone> <Address xmlns="urn:person">3 과 417</Address> - <Person> <Name xmlns="urn:person"> 조흥목 </Name> <ID xmlns="urn:person">1204</id> <Phone xmlns="urn:person">041-550-3490</phone> <Address xmlns="urn:person">2 과 315</Address> - <Person> <Name xmlns="urn:person"> 박정서 </Name> <ID xmlns="urn:person">1203</id> <Phone xmlns="urn:person">041-550-3490</phone> <Address xmlns="urn:person">2 과 315</Address> </ArrayOfPerson> Serialize multiple objects into the same stream 1 개의스트림안에서여러개의클래스객체를 serialize Person person = new Person(textBox1.Text, int.parse(textbox2.text), int x = int.parse(combobox1.items[combobox1.selectedindex].tostring()); int y = int.parse(combobox2.items[combobox2.selectedindex].tostring()); Point point = new Point(x,y); WeatherInfo weather = new WeatherInfo(double.Parse(textBox5.Text), double.parse(textbox6.text), double.parse(textbox7.text)); FileStream fs = new FileStream(@"C:\MultipleObjects.bin", FileMode.Create, BinaryFormatter formatter = new BinaryFormatter(); // serialize multiple objects into the stream formatter.serialize(fs, person); formatter.serialize(fs, point); formatter.serialize(fs, weather);

Serialize multiple objects into the same stream 1 개의스트림안에서여러개의클래스객체를 deserialize private void button2_click(object sender, EventArgs e) { FileStream fs = new FileStream(@"C:\MultipleObjects.bin", FileMode.Open, FileAccess.Read); BinaryFormatter formatter = new BinaryFormatter(); Person person = (Person)formatter.Deserialize(fs); Point point = (Point)formatter.Deserialize(fs); WeatherInfo weather = (WeatherInfo)formatter.Deserialize(fs); textbox1.text = person.name.tostring(); textbox2.text = person.id.tostring(); textbox3.text = person.phone.tostring(); textbox4.text = person.address.tostring(); combobox1.text = point.x.tostring(); combobox2.text = point.y.tostring(); textbox5.text = weather.temperature.tostring(); textbox6.text = weather.wind.tostring(); textbox7.text = weather.humidity.tostring(); Create a new XML file using XmlDocument FileStream stream = File.Open(FileName, FileMode.OpenOrCreate); XmlDocument xmldoc = new XmlDocument(); XmlNode nodepersonlist = xmldoc.createnode("element", "PersonList", ""); foreach (Person p in plist) { XmlNode nodeperson = xmldoc.createnode("element", "Person", ""); XmlNode nodename = xmldoc.createnode("element", "Name", ""); nodename.innertext = Convert.ToString(p.Name); XmlNode nodeid = xmldoc.createnode("element", "ID", ""); nodeid.innertext = Convert.ToString(p.ID); XmlNode nodephone = xmldoc.createnode("element", "Phone", ""); nodephone.innertext = Convert.ToString(p.Phone); XmlNode nodeaddress = xmldoc.createnode("element", "Address", ""); nodeaddress.innertext = Convert.ToString(p.Address); nodeperson.appendchild(nodename); nodeperson.appendchild(nodeid); nodeperson.appendchild(nodephone); nodeperson.appendchild(nodeaddress); nodepersonlist.appendchild(nodeperson); xmldoc.appendchild(nodepersonlist); xmldoc.save(stream); stream.close(); Load a XML file using XmlDocument FileStream stream = File.Open(FileName, FileMode.OpenOrCreate, FileAccess.Read); XmlDocument xmldoc = new XmlDocument(); xmldoc.load(stream); XmlNode nodepersonlist; nodepersonlist = xmldoc.firstchild; foreach (XmlNode nodeperson in nodepersonlist) { Person p = new Person(); p.name = nodeperson.firstchild.innertext; p.id = Int32.Parse(nodePerson.FirstChild.NextSibling.InnerText); p.phone = nodeperson.firstchild.nextsibling.nextsibling.innertext; p.address = nodeperson.lastchild.innertext; plist.add(p); stream.close();