JavaScriptSerializer对Json对象的序列化和反序列化
JavaScriptSerializer对Json对象的序列化和反序列化在使用JavaScriptSerializer对Json对象的序列化和反序列化时,特别需要注意对日期要特殊处理。
一、序列化
public static string SerToJson(object model)
{
return SerToJson(model,"yyyy-MM-dd HH:mm:ss");
}
public static string SerToJson(object model,string format)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
string strJson= jsonSerializer.Serialize(model);
strJson = Regex.Replace(strJson, @"\\\\/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(format);
});
return strJson;
}
二、反序列化
public static T DesFromJson<T>(string strJson) where T : new()
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
T model = jsonSerializer.Deserialize<T>(strJson);
if (model == null)
model = new T();
return model;
}