public static string ObjectToJson<T>(T t)
{
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
serializer.WriteObject(ms, t);
ms.Position = 0;
using (StreamReader reader = new StreamReader(ms))
{
string json = reader.ReadToEnd();
string p = @"\/Date((d+)+d+)\/";
MatchEvaluator evaluator = new MatchEvaluator(ConvertJsonDataToDataString);
Regex reg = new Regex(p);
json = reg.Replace(json, evaluator);
return json;
}
}
}
public static T JsonToObject<T>(string json)
{
string p = @"d{4}-d{2}-d{2}sd{2}:d{2}:d{2}";
MatchEvaluator evaluator = new MatchEvaluator(ConvertDateStringToJsonDate); //对时间进行处理
Regex reg = new Regex(p);
json = reg.Replace(json, evaluator);
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T data = (T)serializer.ReadObject(ms);
return data;
}
}
/// <summary>
/// 将Json时间转换为时间字符
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private static string ConvertJsonDataToDataString(Match m)
{
string result = string.Empty;
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
dt = dt.ToLocalTime();
result = dt.ToString("yyyy-MM-dd HH:mm:ss");
return result;
}
/// <summary>
/// 将时间字符转换成JSON时间
/// </summary>
private static string ConvertDateStringToJsonDate(Match m)
{
string result = string.Empty;
DateTime dt = DateTime.Parse(m.Groups[0].Value);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - DateTime.Parse("1970-01-01");
result = string.Format("\/Date({0}+0800)\/", ts.TotalMilliseconds);
return result;
}
[DataContract]
public class RecentVisitors
{
[DataMember]
public long UserId { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember]
public DateTime Dt { get; set; }
}
var jsonStr="[{"UserId":"123123","UserName":"小小苏","Dt":"2012-09-25 10:50:00"},{"UserId":"456456","UserName":"大头","Dt":"2012-09-25 10:50:00"}]";
调用:
1:JsonToObject<List<RecentVisitors>>(jsonStr)
2:ObjectToJson<List<RecentVisitors>>(new List<RecentVisitors);