【问题标题】:The JSON value could not be converted to System.Nullable`1[System.DateTime [duplicate]JSON 值无法转换为 System.Nullable`1[System.DateTime [重复]
【发布时间】:2022-02-03 07:17:12
【问题描述】:

我有一个可以为空的 DateTime 属性的模型

public DateTime? DateOfBirth { get; set; }

使用以下属性值调用 API 时

{       "Country": "US",
       "State": "New York",
       "Zip" : "123455",
       "dateOfBirth": "8/15/62"
}

这个错误是由.net框架抛出的:

"errors": {
        "$.dateOfBirth": [
            "The JSON value could not be converted to System.Nullable`1[System.DateTime]. Path: $.dateOfBirth | LineNumber: 9 | BytePositionInLine: 33."
        ]

解析似乎适用于其他日期格式,如 yyyy-mm-dd,但不适用于上面示例中提到的格式。

【问题讨论】:

  • 如果你想知道它是否是格式,你是否考虑过用不同的格式调用它来验证你的假设?
  • @mason 是的,我有,似乎可以与其他格式一起使用,但我想知道为什么在解析时不支持这种格式
  • 好的,所以您知道您在帖子中提出的问题的答案。也许你问错了问题,应该编辑你的帖子来问你真正想知道的事情?
  • @mason 更新了问题,现在你有什么有用的要提的吗?
  • 您已更新帖子...但现在它完全没有问题。 Stack Overflow 是一个基于问题的网站。你想知道什么?您想知道如何将这种格式的数据发布到您的 API 中吗?或者你想知道为什么它不像写的那样工作吗?这些是不同的问题,需要不同的答案。因此,您需要具体说明您的要求。如果您觉得我的 cmets 到目前为止没有帮助,我很抱歉,但是指导您如何提出一个好的问题实际上是非常重要的事情。

标签: .net asp.net-core datetime .net-core


【解决方案1】:

我使用 Newtonsoft.Json 对其进行了反序列化,并且在此过程中没有错误。我用过这个类

public class Root
{
    public string Country { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    public DateTime? dateOfBirth { get; set; }
}

但我的 Windows CultureInfo("en-US")。如果您的文化信息不同或正在使用另一个序列化程序并且有问题,我建议您将 DateTime 类型更改为字符串,并尝试在反序列化后转换 ToDateTime。

DateTime 格式取决于 Windows 设置中的区域文化,因此,如果美国的日期时间字符串格式(如您的 json 格式)但您在欧洲,您将始终收到错误消息,因此恕我直言,您最好使用此代码,因为您可以选择 json 的文化,而不是 Windows 默认的。

public class Root
{
    public string Country { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }

     [JsonProperty("dateOfBirth")]
    private string DateOfBirth { get; set; }
    
    [JsonIgnore]
    public DateTime? dateOfBirth
    {
        get { return DateTime.Parse(DateOfBirth, new CultureInfo("en-US")); }
    }
}

【讨论】:

  • 我正在使用来自命名空间 System.Text.Json 的 .net 自己的反序列化器
  • @Sameed System.Text.Json 是垃圾,您只会遇到问题。换成 Newtonsoft 一个。
  • 做了更多测试,看起来像 text.Json 只解析格式为 yyyy-mm-dd 的日期,这与地区文化有关吗?我在欧洲。
  • @Serge 我从来没有遇到过 System.Text.Json 的问题。这个问题完全在 System.Text.Json 的使用范围内。好奇你为什么这么认为?
  • @Serge 至少 100 行?听起来你一次都不知道怎么做,然后就永远注销了。我从来没有发现任何使用自定义转换器无法完成的事情(它将转换从您的模型中抽象出来,从而产生更清晰的代码)。
猜你喜欢
  • 2020-10-05
  • 2020-05-09
  • 2020-03-12
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 2015-04-19
相关资源
最近更新 更多