遗忘的代码

在编程中寻找艺术,享受新的体验。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

#region 获取XML的序列化和反序列化
/// <summary>
/// 对象进行序列化生成XML
/// </summary>
/// <typeparam name="T">需要序列化的对象类型</typeparam>
/// <param name="obj">需要序列化的对象</param>
/// <returns>序列化后的XML</returns>
public static string DataContractXmlSerialize<T>(T obj)
{
if (obj == null)
{
return null;
}
string ret = "";
using (MemoryStream stream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
using (XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
{
serializer.WriteObject(binaryDictionaryWriter, obj);
binaryDictionaryWriter.Flush();
}
ret = Encoding.UTF8.GetString(stream.ToArray());
}
return ret;
}
/// <summary>
/// XML反序列化生成对象
/// </summary>
/// <typeparam name="T">反序列化生成对象类型</typeparam>
/// <param name="xml">XML内容</param>
/// <returns>反序列化生成对象</returns>
public static T DataContractXmlDeserialize<T>(string xml)
{
T ret = default(T);
if (string.IsNullOrEmpty(xml))
{
return ret;
}
using (MemoryStream stream = new MemoryStream())
{
byte[] bytes = Encoding.UTF8.GetBytes(xml);
stream.Write(bytes, 0, bytes.Length);
stream.Position = 0L;
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
using (XmlDictionaryReader binaryDictionaryReader = XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max))
{
ret = (T)serializer.ReadObject(binaryDictionaryReader);
}
}
return ret;
}
#endregion

#region 获取JSON的序列化和反序列化
/// <summary>
/// JSON序列化
/// </summary>
public static string DataContractJsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}

/// <summary>
/// JSON反序列化
/// </summary>
public static T DataContractJsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
#endregion

posted on 2014-04-22 16:23  遗忘的代码  阅读(259)  评论(0编辑  收藏  举报