您的位置:首页 > 其它

Dictionary序列化和反序列化

2014-08-16 08:47 337 查看
public class SerializeHelper
{
public static string XmlSerialize(List<CustomSearchEntity> obj)
{
XmlSerializer serializer = new XmlSerializer();
return serializer.Serialization(obj, typeof(List<CustomSearchEntity>));
}

public static List<CustomSearchEntity> XmlDeserialize(string xmlStr, Dictionary<string, string> historySearchKeyMapping)
{
List<CustomSearchEntity> list = new List<CustomSearchEntity>();
XmlSerializer serializer = new XmlSerializer();
byte[] array = Encoding.UTF8.GetBytes(xmlStr);
MemoryStream stream = new MemoryStream(array);
list = (List<CustomSearchEntity>)serializer.Deserialize(stream, typeof(List<CustomSearchEntity>));
list.ForEach(item =>
{
if (historySearchKeyMapping.Keys.Contains(item.CustomSearchCategory))
{
item.CustomSearchCategory = historySearchKeyMapping.FirstOrDefault(p => p.Key == item.CustomSearchCategory).Value;
}
});
return list;

}
}

public class DictionarySerializeHelper
{
public static string SerializeDictionary(Dictionary<string, string> dataitems)
{
List<DataItem> tempdataitems = new List<DataItem>(dataitems.Count);
foreach (string key in dataitems.Keys)
{
tempdataitems.Add(new DataItem(key, dataitems[key].ToString()));
}
XmlSerializer xs = new XmlSerializer();
return xs.Serialization(tempdataitems, typeof(List<DataItem>));
}

//Proj_10969;XAB-3422;Ken
public static Dictionary<string, string> DeserializeDictionary(string RawData, Dictionary<string, string> historySearchKeyMapping)
{
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
XmlSerializer xs = new XmlSerializer();
byte[] array = Encoding.UTF8.GetBytes(RawData);
MemoryStream stream = new MemoryStream(array);
List<DataItem> templist = (List<DataItem>)xs.Deserialize(stream, typeof(List<DataItem>));
foreach (DataItem di in templist)
{
if (historySearchKeyMapping.Keys.Contains(di.Key))
{
myDictionary.Add(historySearchKeyMapping.FirstOrDefault(p => p.Key == di.Key).Value, di.Value);
}
else
{
myDictionary.Add(di.Key, di.Value);
}
}
return myDictionary;
}
}

public class DataItem
{
public DataItem()
{
}
public string Key;
public string Value;

public DataItem(string key, string value)
{
Key = key;
Value = value;
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: