/// <summary>
/// 序列化对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="obj">对象</param>
/// <returns>序列化的 Json 字符串</returns>
public static string Serialize<T>(T obj) where T : class
{
if (obj == null)
{
return null;
}
try
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
MemoryStream msObj = new MemoryStream();
//将序列化之后的Json格式数据写入流中
js.WriteObject(msObj, obj);
msObj.Position = 0;
//从0这个位置开始读取流中的数据
StreamReader sr = new StreamReader(msObj, JSON_ENCODING);
string json = sr.ReadToEnd();
sr.Close();
msObj.Close();
return json;
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("序列化对象为 Json 格式出错,消息={0}, 堆栈={1}", ex.Message, ex.StackTrace));
return null;
}
}
/// <summary>
/// 反序列化对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">序列化的 Json 字符串</param>
/// <returns>对象</returns>
public static T Deserialize<T>(string json) where T : class
{
if (string.IsNullOrEmpty(json))
{
return null;
}
try
{
using (var ms = new MemoryStream(JSON_ENCODING.GetBytes(json)))
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
object obj = js.ReadObject(ms);
if (obj == null || !(obj is T))
{
return null;
}
return obj as T;
}
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("反序列化 Json 对象出错,消息={0}, 堆栈={1}", ex.Message, ex.StackTrace));
return null;
}
}
C# 序列化和反序列化
最新推荐文章于 2023-02-20 14:53:07 发布