• .netcore3.0 System.Text.Json 日期格式化


    .netcore3.0 的json格式化不再默认使用Newtonsoft.Json,而是使用自带的System.Text.Json来处理。
    理由是System.Text.Json 依赖更少,效率更高。

    webapi定义的参数如果是个datetime类型的话 比如

    public class Input
    {
         public DateTime?Begin{get;set;}
         public DateTime?End{get;set;}
    }
    
    webapi的controller中定义的action
    
    public dynamic GetList([FromBody]Input input)
    {
       ……
    }
    
    

    这是一个常用的场景

    如果请求传入的 日期格式是 {"begin":"2019-10-12","end":"2019-10-13"} 服务端会报错 无法解析字符串为DateTime类型,
    这时候就需要增加类型转换的处理方式

    
        public class SystemTextJsonConvert
        {
            public class DateTimeConverter : JsonConverter<DateTime>
            {
                public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
                {
                    return DateTime.Parse(reader.GetString());
                }
    
                public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
                {
                    writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
                }
            }
    
            public class DateTimeNullableConverter : JsonConverter<DateTime?>
            {
                public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
                {
                    return string.IsNullOrEmpty(reader.GetString()) ? default(DateTime?) : DateTime.Parse(reader.GetString());
                }
    
                public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
                {
                    writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss"));
                }
            }
        }
    

    JsonConverter中包含 read和write的抽象方法 ,只要重写这两个方法,规定输入转换的方式和输出格式化的方法就行了。

    在 setup中增加配置

      services.AddControllers().AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.Converters.Add(new Common.SystemTextJsonConvert.DateTimeConverter());
                    options.JsonSerializerOptions.Converters.Add(new Common.SystemTextJsonConvert.DateTimeNullableConverter());
                }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
    

    这个时候再请求接口,就能正常转换日期类型了,
    同样返回日期格式不是在 日期和时间中间有个 “T” 了,而是 yyyy-MM-dd HH:mm:ss正常的格式了。

  • 相关阅读:
    CF1066D Boxes Packing
    luogu P2508 [HAOI2008]圆上的整点
    luogu P2502 [HAOI2006]旅行
    luogu P2511 [HAOI2008]木棍分割
    luogu P4161 [SCOI2009]游戏
    luogu P4160 [SCOI2009]生日快乐
    windows2012系统IE浏览器无法打开加载flashplayer内容
    kvm虚拟机相关
    esxI开启虚拟化
    Termux 详细安装
  • 原文地址:https://www.cnblogs.com/sands/p/11662622.html
Copyright © 2020-2023  润新知