ServiceStack.文本JsonSerializer - SerializeToString失败的白色DateTi
本文关键字:白色 DateTi 失败 SerializeToString 文本 JsonSerializer ServiceStack | 更新日期: 2023-09-27 18:09:01
我正在使用ServiceStack。使用c#的web应用程序上的文本JsonSerializer。问题是,对于一个特定的功能,我需要序列化日期值为json,但目前失败时,值是DateTime.MaxValue。
下面是一些代码示例来复制这一点(这是一个简单的控制台应用程序):class Program
{
static void Main(string[] args)
{
var jsonResultMin = JsonSerializer.SerializeToString<DateTime>(DateTime.MinValue);
var deJsonMin = JsonSerializer.DeserializeFromString<DateTime>(jsonResultMin);
Console.WriteLine("jsonResultMin" + jsonResultMin);
Console.WriteLine("deJsonMin" + deJsonMin);
var jsonResultMax = JsonSerializer.SerializeToString<DateTime>(DateTime.MaxValue);
var deJsonMax = JsonSerializer.DeserializeFromString<DateTime>(jsonResultMax);
Console.WriteLine("jsonResultMax" + jsonResultMax);
Console.WriteLine("deJsonMax" + deJsonMax);
Console.ReadLine();
}
}
堆栈跟踪为:
System.ArgumentOutOfRangeException was unhandled
HResult=-2146233086
Message=The added or subtracted value results in an un-representable DateTime.
Parameter name: value
Source=mscorlib
ParamName=value
StackTrace:
at System.DateTime.Subtract(TimeSpan value)
at ServiceStack.Text.DateTimeExtensions.ToDateTimeSinceUnixEpoch(DateTime dateTime)
at ServiceStack.Text.DateTimeExtensions.ToUnixTimeMs(DateTime dateTime)
at ServiceStack.Text.Common.DateTimeSerializer.WriteWcfJsonDate(TextWriter writer, DateTime dateTime)
at ServiceStack.Text.Json.JsonTypeSerializer.WriteDateTime(TextWriter writer, Object oDateTime)
at ServiceStack.Text.Json.JsonWriter`1.WriteRootObject(TextWriter writer, Object value)
at ServiceStack.Text.JsonSerializer.SerializeToString[T](T value)
at ConsoleApplication1.Program.Main(String[] args)
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
我理解错误是由于ServiceStack库在内部进行日期-时间转换而发生的。
另外,我发现如果从最大值中减去一天(addDays(-1)),库不会失败。
但是有没有一种方法可以在不修改日期的情况下使此工作?
错误是Unix时间转换的结果,如果您设置了DateHandler,则可以跳过它,如:
JsConfig.DateHandler = DateHandler.ISO8601DateTime
如果您想检查所有可能的转换,请检查源代码
可以使用以下命令跳过UTC日期时间转换:
JsConfig.SkipDateTimeConversion = true;