简体   繁体   English

.net DateTime序列化反序列化错误

[英].net DateTime Serialization Deserialization bug

If you serialize and deserialize a DateTime using embedded .net JavaScriptSerializer, you get two different dates if you are in UTC+something ! 如果使用嵌入式.net JavaScriptSerializer序列化和反序列化DateTime,则如果使用UTC + something,则会得到两个不同的日期!

Example (suppose you are in UTC+2 like I am now) 示例(假设您现在像现在一样处于UTC + 2)

JavaScriptSerializer myJson = new JavaScriptSerializer();

DateTime myDate = DateTime.Now; //suppose 2016-03-29 16:12:00
strSerialized = myJson.Serialize(myDate);

//DO WHAT YOU NEED WITH IT...

DateTime myDateDes = myJson.Deserialize<DateTime>(strSerialized);
Label1.Text=myDateDes.ToString();//it gives you 2016-03-29 14:12:00 ! WRONG! IT's in UTC+0 ! Has 2 HOURS less !!!

So, when you get the deserialized date, it'll give you the UTC+0 value by default...!! 因此,当您获得反序列化日期时,默认情况下它将为您提供UTC + 0值...!

This is different from JavaScriptSerializer UTC DateTime issues because that article describes the difference in deserialization of different datetime data types, and provides a solution (.UtcDateTime) that doesn't fix the problem. 这与JavaScriptSerializer UTC DateTime问题不同,因为该文章描述了不同日期时间数据类型的反序列化的区别,并提供了不能解决问题的解决方案(.UtcDateTime)。 In fact, trying to deserialize with .utcDateTime a serialized DateTime always gives you the wrong UTC+0 date... 实际上,尝试使用.utcDateTime反序列化序列化的DateTime总是会给您错误的UTC + 0日期...

There are two different solutions: either use ToLocalTime() when you deserialize OR use the Newtonsoft.Json. 有两种不同的解决方案:在反序列化时使用ToLocalTime()或使用Newtonsoft.Json。

So the same code, "fixed", in the first case should be: 因此,在第一种情况下,相同的代码“固定”应为:

JavaScriptSerializer myJson = new JavaScriptSerializer();

DateTime myDate = DateTime.Now; //suppose 2016-03-29 16:12:00
strSerialized = myJson.Serialize(myDate);

//DO WHAT YOU NEED WITH IT...

DateTime myDateDes = myJson.Deserialize<DateTime>(strSerialized).ToLocalTime();

Label1.Text=myDateDes.ToString();//it gives you 2016-03-29 16:12:00 !!! CORRECT !

Otherwise, using Newtonsoft.Json (you first need to install it from nuGet, then add a "using Newtonsoft.Json" at the top), and use it like this: 否则,请使用Newtonsoft.Json(您首先需要从nuGet安装它,然后在顶部添加“ using Newtonsoft.Json”),并按如下方式使用它:

DateTime myDate = DateTime.Now; //suppose 2016-03-29 16:12:00
strSerialized = JsonConvert.SerializeObject(myDate);

//DO WHAT YOU NEED WITH IT...

DateTime myDateDes = JsonConvert.DeserializeObject<DateTime>(strSerialized);
Label1.Text=myDateDes.ToString();//NO need to convert to LocalTime... it already gives you 2016-03-29 16:12:00 !!! CORRECT !

I hope this will be useful for someone else... I googled a lot and found nothing about this problem that only happens with Microsoft serializer... 我希望这对其他人有用。我在Google上搜索了很多,却对这个只有Microsoft序列化程序才能解决的问题一无所获...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM