如何将空字符串值转换为可为空的日期值?

Sky*_*ell 2 c# entity-framework-core asp.net-core-webapi

当我使用 Postman 通过 PUT 请求测试我的 API 时,出现以下错误:

"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-fe50a5f13435f11ef5d27de5f91d3c45-47c1ee82a70305a9-00",
"errors": {
    "$.extractionDate": [
        "The JSON value could not be converted to System.Nullable`1[System.DateTime]. Path: $.extractionDate | LineNumber: 0 | BytePositionInLine: 704."
    ]
}
Run Code Online (Sandbox Code Playgroud)

我可以看到一个看起来像这样的空字符串被传递给 API:

"extractionDate":""
Run Code Online (Sandbox Code Playgroud)

在我的模型中,我将ExtractionDate属性设置为可为空,如下所示:

public DateTime? ExtractionDate { get; set; }
Run Code Online (Sandbox Code Playgroud)

由于超出我控制范围的事情,使用此 API 的旧系统无法传递 null,它只能为任何 null 值传递空白字符串。

为了使 JSON 有效,我还需要做其他事情吗?

谢谢!

Jos*_*son 6

好吧,假设您可以控制 API 和模型,您可以编写一个通过返回 来JsonConverter<DateTime?>处理空的自定义。stringnull

一个简单的实现JsonConverter<DateTime?>可能看起来像这样......

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

public class NullableDateTimeConverter : JsonConverter<DateTime?>
{
    public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var @string = reader.GetString();
        if (string.IsNullOrWhiteSpace(@string))
        {
            return null;
        }
        return DateTime.Parse(@string);
    }

    public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
    {
        if (value != null)
        {
            writer.WriteStringValue(value.Value.ToString("o"));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以告诉您的模型将其与JsonConverterAttribute.

using System;
using System.Test.Json.Serialization;

public class TheModel
{
    [JsonConverter(typeof(NullableDateTimeConverter))]
    public DateTime? ExtractionDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)