我正在尝试通过从标头中获取日期并将遇到错误来将JSON字符串转换为DateTime。
我的代码:
if (actionContext.Request.Headers.Contains("DataSync"))
{
var date = actionContext.Request.Headers.GetValues("DataSync").First();
userRequest.LastSync =
JsonConvert.DeserializeObject<DateTime>(date,new IsoDateTimeConverter());
}
错误:
"Message": "An error has occurred.",
"ExceptionMessage": "Error reading date. Unexpected token: Integer. Path '', line 1, position 2.",
"ExceptionType": "Newtonsoft.Json.JsonReaderException",
"StackTrace": " em Newtonsoft.Json.JsonReader.ReadAsDateTimeInternal()\ \ em Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)\ \ em Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\ \ em Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\ \ em Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)\ \ em Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)\ \ em Portal.Infraestructure.Filters.UserRequestFilter.OnActionExecuting(HttpActionContext actionContext) na d:\\Projetos\\api\\Portal\\Infraestructure\\Filters\\UserRequestFilter.cs:linha 28\ \ em System.Web.Http.Filters.ActionFilterAttribute.OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)\ \ --- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---\ \ em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\ \ em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\ \ em System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\ \ --- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---\ \ em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\ \ em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\ \ em System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\ \ em System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\ \ --- Fim do rastreamento de pilha do local anterior onde a exceção foi gerada ---\ \ em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\ \ em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\ \ em System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\ \ em System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
我正在使用邮递员进行测试。我正在调用我的控制器并在邮递员的标题中传递日期。 我该怎么做才能解决这个错误?
答案 0 :(得分:1)
也许使用日期时间格式就可以了。
var format = "dd/MM/yyyy";
var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = format };
var ld = JsonConvert.DeserializeObject<DateTime>(json, dateTimeConverter);
答案 1 :(得分:-1)
<强>解决方案:强>
使用DateTime.Parse()