【问题标题】:Allow specific datetime formats in asp.net core app on json deserialization在 json 反序列化时允许在 asp.net 核心应用程序中使用特定的日期时间格式
【发布时间】:2019-01-29 16:47:22
【问题描述】:

我想在我的 asp.net 核心应用程序中允许特定的日期时间格式。

我在 Startup.cs 的 ConfigureServices 方法中有这段代码:

...

services.AddMvc()
.AddJsonOptions(options =>
{
   ...
   options.SerializerSettings.DateFormatString = "dd/MM/yyyy HH:mm";
})

...

此属性只允许一种日期时间格式。

我需要这样的东西(允许许多日期时间格式):

...

services.AddMvc()
.AddJsonOptions(options =>
{
   ...
   options.SerializerSettings.DateFormatString = { "dd/MM/yyyy HH:mm", "dd/MM/yyyy HH:mm:ss", "dd/MM/yyyy", ... };
});

...

谢谢。

【问题讨论】:

  • 您必须在 C# 代码中执行此操作,然后将其作为 JSON 字符串发送。

标签: asp.net-core json.net json-deserialization


【解决方案1】:

这是不可能的。从逻辑上讲,序列化程序如何知道实际应用哪种格式?没有Date 类型,所以DateTime,即使它没有设置时间组件仍然是DateTime,并且会简单地将时间返回为午夜(00:00:00)。

您在这里遇到了 API 设计中的一个基本缺陷。 API 不应为相同的成员返回不同的类型。如果时间永远是一个组成部分,那么时间应该始终存在,即使它被归零。返回不同的响应会给客户带来额外的,有时甚至是不可能的负担。

【讨论】:

  • 在一些 ASP.NET 项目(没有 .net 核心)中,我使用了这种类型的自定义转换器类:link
  • 我需要类似的东西来反序列化 json。
  • 您可以通过在 DTO 类上定义自定义值解析器来控制它。每个 DTO 将只能响应一种特定格式,但您可以在不同的场景中使用不同的 DTO。
  • 我不相信这是“不可能的”。在一些限制条件下是可能的。我使用docs.microsoft.com/en-us/dotnet/standard/datetime/… 来弥补我的输入数据采用宽松的 ISO 8601 格式(日期和时间之间没有“T”)这一事实,但该代码适用于任何明确的日期格式。像“2000 年 1 月 2 日”这样的日期仍然会出现问题
【解决方案2】:

来自https://docs.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support

public class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        Debug.Assert(typeToConvert == typeof(DateTime));
        return DateTime.Parse(reader.GetString());
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString());
    }
}

class Program
{

    private static void ProcessDateTimeWithCustomConverter()
    {
        JsonSerializerOptions options = new JsonSerializerOptions();
        options.Converters.Add(new DateTimeConverterUsingDateTimeParse());

        string testDateTimeStr = "04-10-2008 6:30 AM";
        string testDateTimeJson = @"""" + testDateTimeStr + @"""";

        DateTime resultDateTime = JsonSerializer.Deserialize<DateTime>(testDateTimeJson, options);
        Console.WriteLine(resultDateTime);

        string resultDateTimeJson = JsonSerializer.Serialize(DateTime.Parse(testDateTimeStr), options);
        Console.WriteLine(Regex.Unescape(resultDateTimeJson));
    }
}

应该处理任何明确的日期/时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 2020-09-01
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    相关资源
    最近更新 更多