【问题标题】:The JSON value could not be converted to System.DateTime [duplicate]JSON 值无法转换为 System.DateTime [重复]
【发布时间】:2020-05-09 00:56:57
【问题描述】:

我有一个Employee

public class Employee
{
   [Key]
   public long ID { get; set; }
   public DateTime EmpDate { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

我创建了 Web API 来发布员工数据:

[HttpPost]
public async Task<ActionResult<Employee>> PostLead(Employee employee)
{
      //Code to post
}

这是我的 JSON 正文

{
    "firstname":"xyz",
    "lastname":"abc",
    "EmpDate":"2019-01-06 17:16:40"
}

我收到The JSON value could not be converted to System.DateTime. 的错误但是当我将 EmpDate 值作为2019-01-06 传递时,我没有收到错误。

【问题讨论】:

  • 你不能把你的 EmpData 属性改成字符串吗?
  • 使用 ISO 8601 格式:“2019-01-06T17:16:40.000”
  • @LinkedListT 是的,我可以。但是,还有很多其他功能依赖于 DateTime EmpDate。
  • 顺便说一句,但是,假设您的 JSON 来自 JavaScript,请在​​ JS 端使用 Date.toISOString; ASP.NET 可以很好地处理 ISO 字符串。
  • 大家好,ISO 8601 在 Postman 中为我工作。我现在将在代码中更新。谢谢大家。

标签: c# json asp.net-core-webapi json-deserialization


【解决方案1】:

您在 JSON 中的日期值不正确。应该是

2019-01-06T17:16:40

大多数解析器使用ISO 8601

【讨论】:

  • 其实json中的日期时间值并没有错。它应该被视为“自定义格式”。尽管大多数解析器默认使用 ISO 8601,但这并不意味着你/他/我必须使用它。字符串数据解析是业务逻辑的一个问题,如果我需要使用“yyyy-MM-dd hh:mm:ss”格式,那么我需要说解析器使用该格式。这样想。您正在进行第 3 方集成,但他们并没有改变格式,例如他们是支付网关提供商,并在全球范围内广泛使用。
  • 也可以使用new Date(stringValue).toISOString()
  • 您可能还想指定一个时区,例如 2019-01-06T17:16:40Z(最后的 Z 表示它是 UTC)
猜你喜欢
  • 1970-01-01
  • 2020-10-05
  • 2019-05-19
  • 2015-07-09
  • 1970-01-01
  • 2011-02-25
  • 1970-01-01
相关资源
最近更新 更多