/// <summary>
/// 序列化请求数据 格式化字符串,不包含换行字符
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string Serialize<T>(T t)
{
MemoryStream stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(t.GetType());
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.GetEncoding("GBK"));
writer.Formatting = Formatting.None;
try
{
xml.Serialize(writer, t);
}
catch (InvalidOperationException)
{
throw new ApplicationException("序列化异常!");
}
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("GBK"));
stream.Position = 0;
StringBuilder sb = new StringBuilder();
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
reader.Close();
writer.Close();
return sb.ToString(); ;
}
/// <summary>
/// 序列化请求数据 未格式化字符串 包含换行符 \r\n
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string Serialize<T>(T t)
{
MemoryStream stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(t.GetType());
//XmlTextWriter writer = new XmlTextWriter(stream, Encoding.GetEncoding("GBK"));
StreamWriter writer = new StreamWriter(stream, Encoding.GetEncoding("GBK"));
//writer.Formatting = Formatting.None;
try
{
xml.Serialize(writer, t);
}
catch (InvalidOperationException)
{
throw new ApplicationException("序列化异常!");
}
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("GBK"));
//stream.Position = 0;
//StringBuilder sb = new StringBuilder();
//string line;
//while ((line = reader.ReadLine()) != null)
//{
// sb.Append(line);
//}
//reader.Close();
//writer.Close();
stream.Position = 0;
string sr = reader.ReadToEnd();
string head = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"";
string strs = sr.Replace(head, "");
return strs.ToString();
}
/// <summary>
/// 反序列化响应内容(反序列化为对象)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="responseData"></param>
/// <returns></returns>
public static T Deserialize<T>(string responseData)
{
XmlSerializer xmls = new XmlSerializer(typeof(T));
StringReader reader;
T result=default(T);
try
{
reader = new StringReader(responseData);
result= (T)xmls.Deserialize(reader);
}
catch (Exception ex) { }
return result;
}