以下是代码:
实体
public class jsonmm
{
public string Name { get; set; }
public int Age { get; set; }
//[ScriptIgnore]
public DateTime LastLoginTime { get; set; }
}
方法:
public string ScriptSerialize<T>(T t)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(t);
}
页面测试:
Code.json pp = new Code.json();
Code.jsonmm p = new Code.jsonmm();
p.Name = "张三";
p.Age = 28;
p.LastLoginTime = DateTime.Now.ToUniversalTime();
string jsonString = pp.ScriptSerialize<Code.jsonmm>(p);
Response.Write(jsonString);
时间已经转换为utc格式了,可还是得出这样的数据
{"Name":"张三","Age":28,"LastLoginTime":"\/Date(1313572554031)\/"}
怎么修改呢
=====================================================================
JavaScriptSerializer的行为是这样的,你可以在客户端再处理一下
1
2
3
4
|
var json = { "Name" : "张三" , "Age" : 28, "LastLoginTime" : "\/Date(1313572554031)\/" };
//把/删除,并转换为正确的javascript时间 json.LastLoginTime = eval( 'new ' + (json.LastLoginTime.replace(/\ //g, '')));
alert(json.LastLoginTime); |
1
2
3
4
5
6
7
8
9
10
11
12
|
Model m = new Model { Id = 1, Dt = DateTime.Now };
JavaScriptSerializer js = new JavaScriptSerializer();
string str = js.Serialize(m);
str = Regex.Replace(str, @"\\/Date\((\d+)\)\\/" , match =>
{
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds( long .Parse(match.Groups[1].Value));
dt = dt.ToLocalTime();
return dt.ToString( "yyyy-MM-dd HH:mm:ss" );
});
Response.Write(str);
//{"Id":1,"Dt":"2011-08-17 17:38:47"} |