JavaScriptSerializer 在序列化时间datetime类型是会有时区差异

JavaScriptSerializer  与    DataContractJsonSerializer(命名空间System.ServiceModel.Web及System.Runtime.Serialization)


JavaScriptSerializer   在序列化时间datetime类型是会有时区差异,JavaScriptSerializer 会将时间转成utc类型

DataContractJsonSerializer  在序列化时间时对时间类型进行了判断,如果为local类型,则加上时区

因此推荐使用DataContractJsonSerializer 序列化

 1     public class JsonHelper

 2     {

 3         public static string Serialize<T>(T data)

 4         {

 5             System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =

 6             new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());

 7             using (MemoryStream ms = new MemoryStream())

 8             {

 9                 serializer.WriteObject(ms, data);

10                 return Encoding.UTF8.GetString(ms.ToArray());

11             }

12         }

13 

14         public static T Deserialize<T>(string json)

15         {

16             T obj = Activator.CreateInstance<T>();

17             using (MemoryStream ms =

18             new MemoryStream(Encoding.UTF8.GetBytes(json)))

19             {

20                 System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =

21                 new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());

22                 return (T)serializer.ReadObject(ms);

23             }

24         }

25 

26     }

你可能感兴趣的:(JavaScript)