我正在使用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)),库就不会失败。
但有没有一种解决方法可以在不修改日期的情况下完成这项工作?
答案 0 :(得分:2)
错误是由Unix时间转换产生的,如果设置DateHandler,可以跳过它,如:
JsConfig.DateHandler = DateHandler.ISO8601DateTime
如果您想检查所有可能的转化,请查看source code
答案 1 :(得分:1)
您可以使用以下命令跳过UTC DateTime转换:
JsConfig.SkipDateTimeConversion = true;