.Net3.5扩展方法实现对象JSON序列化
.NET 3.5 还包含一个新的new System.Runtime.Serialization.DataContractJsonSerializer class 类 ,你也可以用它来做JSON (JavaScript Object Notation)序列化/反序列化的工作。
/// <summary>
/// Json数据转换封装
/// </summary>
public static class JsonHelper
{
/// <summary>
/// 将时间由"\/Date(10000000000-0700)\/" 格式转换成 "yyyy-MM-dd HH:mm:ss" 格式的字符串
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private static string GetDatetimeString(Match m)
{
string sRet = "";
try
{
System.DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
dt = dt.ToLocalTime();
sRet = dt.ToString("yyyy-MM-dd HH:mm:ss");
}
catch
{ }
return sRet;
}
/// <summary>
/// 将时间由 "yyyy-MM-dd HH:mm:ss" 格式的字符串转换成"\/Date(10000000000-0700)\/" 格式
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private static string GetDatetimeJson(Match m)
{
String sRet = "";
try
{
DateTime dt = DateTime.Parse(m.Groups[1].Value);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - DateTime.Parse("1970-01-01");
sRet = string.Format("\\/Date({0}-0700)\\/", ts.TotalMilliseconds);
}
catch
{ }
return sRet;
}
/// <summary>
/// 扩展Object 方法 ToJson
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static String ToJson(this object obj)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
jsonSerializer.WriteObject(ms, obj);
String sRet = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
//将时间由"\/Date(10000000000-0700)\/" 格式转换成 "yyyy-MM-dd HH:mm:ss" 格式的字符串
string sPattern = @"\\/Date\((\d+)-\d+\)\\/";
MatchEvaluator myMatchEvaluator = new MatchEvaluator(GetDatetimeString);
Regex reg = new Regex(sPattern);
sRet = reg.Replace(sRet, myMatchEvaluator);
return sRet;
}
/// <summary>
/// Jason deSerialize
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sJason"></param>
/// <returns></returns>
public static T FromJson<T>(String sJasonData)
{
//将时间由 "yyyy-MM-dd HH:mm:ss" 格式的字符串转换成"\/Date(10000000000-0700)\/" 格式
string sPattern = @"(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})";
MatchEvaluator myMatchEvaluator = new MatchEvaluator(GetDatetimeJson);
Regex reg = new Regex(sPattern);
string src = reg.Replace(sJasonData, myMatchEvaluator);
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(src));
object obj = jsonSerializer.ReadObject(ms);
return (T)obj;
}
}
摘自:http://hi.baidu.com/woxxf/blog/item/66edcf51447d382343a75b5d.html