zoukankan
html css js c++ java
Dictionary在XML序列化时遇到的问题及应对方案
在项目中需要一个Dictionary来保存键值对,类型为Dictionary<string,List<string>>,在向文件流中序列化的时候出现了错误,查询资料发现.net中的XmlSerializer不支持Dictionary,网上有很多应对方案,但都比较复杂,用起来总觉得心里不够踏实(害怕BUG),下面从另一个角度,在序列化和反序列化的时候进行数据类型的转换,从而达到序列化的目的,示例代码如下:
/**/
///
<summary>
///
This class is used for xml serialization on generic type Dictionary
///
</summary>
public
class
DictionaryHolder
{
public
string
logicalName
=
""
;
public
List
<
string
>
physicalNames
=
new
List
<
string
>
();
}
/**/
///
<summary>
///
Loads the specified database.
///
</summary>
///
<param name="database">
The database.
</param>
public
void
load(
string
database)
{
FileStream fs
=
null
;
try
{
XmlSerializer xs
=
new
XmlSerializer(
typeof
(List
<
DictionaryHolder
>
));
fs
=
new
FileStream(database, FileMode.Open, FileAccess.Read, FileShare.Read);
List
<
DictionaryHolder
>
holders
=
(List
<
DictionaryHolder
>
)xs.Deserialize(fs);
this
._dictionary.Clear();
foreach
(DictionaryHolder holder
in
holders)
{
this
._dictionary.Add(holder.logicalName, holder.physicalNames);
}
}
catch
(Exception ex)
{
throw
;
}
finally
{
if
(fs
!=
null
)
fs.Close();
}
}
/**/
///
<summary>
///
Saves the specified database.
///
</summary>
///
<param name="database">
The database.
</param>
public
void
save(
string
database)
{
FileStream fs
=
null
;
try
{
List
<
DictionaryHolder
>
holders
=
new
List
<
DictionaryHolder
>
();
foreach
(
string
key
in
this
._dictionary.Keys)
{
DictionaryHolder holder
=
new
DictionaryHolder();
holder.logicalName
=
key;
holder.physicalNames
=
this
._dictionary[key];
holders.Add(holder);
}
XmlSerializer xs
=
new
XmlSerializer(
typeof
(List
<
DictionaryHolder
>
));
fs
=
new
FileStream(database, FileMode.Create, FileAccess.Write, FileShare.Read);
xs.Serialize(fs, holders);
}
catch
(Exception ex)
{
throw
;
}
finally
{
if
(fs
!=
null
)
fs.Close();
}
}
经测试,可以正常工作,这里我们实际上采用了目标转换的手法,将待序列化的对象转换为自定义的支持序列化的类型,在反序列化的时候首先反序列化为自定义的对象类型,然后再构造最终对象。
个人觉得微软应该针对Dictionary添加XML序列化支持,因为它的数据结构可以很轻易的映射到XML文档中:键值映射为一个节点,该键值对应的对象映射为此节点的子节点。
查看全文
相关阅读:
node.js学习二---------------------同步API和异步API的区别
node.js学习一---------------------模块的导入
ES6函数的特性(箭头语法)
10分钟了解Android的Handler机制
10分钟了解Android的事件分发
SwipeRefreshLayout,用最少的代码定制最美的上下拉刷新样式
手把手教你React Native 实战之开山篇《一》
Android 组件化方案探索与思考
2018谷歌I/O开发者大会8大看点汇总 新品有哪些
Glide高级详解—缓存与解码复用
原文地址:https://www.cnblogs.com/swnuwangyun/p/689812.html
最新文章
计算机组成原理之计算机组成
计算机组成学习之开篇
Java
Redis系列一之《Redis设计与实践》整体观感
Spring-白话事物
java — 抽象类和接口
java面向对象特征 — 一句话概括
接口用例详细
mac删除python
接口自动化python
热门文章
appium长按按钮
python线程 有问题?
网盘抓取资料
自动化部分
使用最终一致性思想解决分布式事务
java解析HTML之神器------Jsoup
node.js学习6---第三方依赖(模块或者说是包)的导入 npm 以及 cnpm命令的使用
node.js学习5--------------------- 返回html内容给浏览器
node.js学习4--------------------- 根据不同路径来响应内容,以及中文乱码的解决
node.js学习三--------------------- http服务器模块的搭建
Copyright © 2011-2022 走看看