十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
宜兴ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:028-86922220(备注:SSL证书合作)期待与您的合作!> public static string ObjectToJson(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(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;
}
}
/// /// 将Json时间转换为时间字符
/// /// /// 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;
}
/// /// 将时间字符转换成JSON时间
/// 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>(jsonStr)
2:ObjectToJson>(new List