성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>XmlSerializer와 Dictionary 타입</h1> <p> Dictionary 타입에 대해 XmlSerializer를 사용하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System.Xml.Serialization; internal class Program { static void Main(string[] args) { MemoryStream ms = new MemoryStream(); <span style='color: blue; font-weight: bold'>Dictionary<string, long></span> dict = new Dictionary<string, long>() { { "1", 1000 }, { "2", 2000 }, { "3", 3000 }, { "4", 4000 }, }; var formatter = new <span style='color: blue; font-weight: bold'>XmlSerializer(typeof(Dictionary<string, long>));</span> formatter.<span style='color: blue; font-weight: bold'>Serialize</span>(ms, dict); ms.Position = 0; dict = <span style='color: blue; font-weight: bold'>formatter.Deserialize(ms) as Dictionary<string, long>;</span> foreach (var key in dict.Keys) { Console.WriteLine($"{key} = {dict[key]}"); } } } </pre> <br /> 다음과 같은 식의 예외가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Unhandled exception. System.NotSupportedException: The type System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int64, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]] is not supported because it implements IDictionary. at System.Xml.Serialization.TypeScope.GetDefaultIndexer(Type type, String memberInfo) at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference) at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError) at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean directReference) at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace) at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace) at System.Xml.Serialization.XmlSerializer..ctor(Type type) at Program.Main(String[] args) in C:\Console1\Console1\Program.cs:line 17 </pre> <br /> 예외 메시지 그대로 XmlSerializer는 IDictionary를 구현한 타입에 대한 직렬화를 지원하지 못합니다. 이에 대한 우회 방법은 2가지입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Why doesn't XmlSerializer support Dictionary? ; <a target='tab' href='https://stackoverflow.com/questions/2911514/why-doesnt-xmlserializer-support-dictionary'>https://stackoverflow.com/questions/2911514/why-doesnt-xmlserializer-support-dictionary</a> </pre> <br /> 정리하면, 1) 직렬화 클래스를 바꾸거나 2) Dictionary 대신 XmlSerializer가 이해할 수 있는 자료 구조를 사용하는 것입니다. 1번 방법의 대표적인 경우가 BinaryFormatter를 사용하는 것인데 이에 대해서는 전에도 한 번 설명한 적이 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Dictionary<TKey, TValue>를 deep copy하는 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/11157'>https://www.sysnet.pe.kr/2/0/11157</a> </pre> <br /> 반면 2번째 방법도 꽤 괜찮습니다. 즉, "XML Serializable Generic Dictionary"를 사용하는 것인데요,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > XML Serializable Generic Dictionary ; <a target='tab' href='https://weblogs.asp.net/pwelter34/444961'>https://weblogs.asp.net/pwelter34/444961</a> XML Serializable Dictionary ; <a target='tab' href='https://learn.microsoft.com/en-us/archive/blogs/amolgote/xml-serializable-dictionary'>https://learn.microsoft.com/en-us/archive/blogs/amolgote/xml-serializable-dictionary</a> </pre> <a name='dict_xml'></a> <br /> nullable 문맥을 약간 조정해 다음과 같이 SerializableDictionary를 만들면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System.Xml.Serialization; [XmlRoot("dictionary")] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue?>, IXmlSerializable where TKey : notnull { #region IXmlSerializable Members public System.Xml.Schema.XmlSchema? GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); TKey? key = (TKey?)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue? value = (TValue?)valueSerializer.Deserialize(reader); reader.ReadEndElement(); if (key != null) { this.Add(key, value); } reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue? value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } } #endregion } </pre> <br /> 이를 사용하는 클래스 측에서는 다음과 같이 Dictionary를 SerializableDictionary로 바꾸기만 하면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MemoryStream ms = new MemoryStream(); <span style='color: blue; font-weight: bold'>SerializableDictionary<string, long>? dict = new SerializableDictionary<string, long>()</span> { { "1", 1000 }, { "2", 2000 }, { "3", 3000 }, { "4", 4000 }, }; var formatter = new XmlSerializer(<span style='color: blue; font-weight: bold'>typeof(SerializableDictionary<string, long>)</span>); formatter.Serialize(ms, dict); ms.Position = 0; dict = formatter.Deserialize(ms) as <span style='color: blue; font-weight: bold'>SerializableDictionary<string, long></span>; if (dict != null) { foreach (var key in dict.Keys) { Console.WriteLine($"{key} = {dict[key]}"); } } /* 출력 결과 1 = 1000 2 = 2000 3 = 3000 4 = 4000 */ </pre> <br /> (첨부 파일은 이 글의 예제 코드를 포함합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
3135
(왼쪽의 숫자를 입력해야 합니다.)