ServiceStack.Text JsonSerializer - SerializeToString 失败 DateTime.Max

ServiceStack.Text JsonSerializer - SerializeToString fails whit DateTime.Max

我在使用 C# 的 Web 应用程序上使用 ServiceStack.Text 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) ),库不会失败。

但是有没有一种解决方法可以在不修改日期的情况下进行这项工作?

您可以跳过 UTC 日期时间转换:

JsConfig.SkipDateTimeConversion = true;

错误是Unix时间转换的结果,如果你设置了一个DateHandler可以跳过它,比如:

JsConfig.DateHandler = DateHandler.ISO8601DateTime

如果您想检查所有可能的转换,请检查 source code