1. 程式人生 > >C# 序列化和反序列化

C# 序列化和反序列化

/// <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;
    }
}