关于The JSON value could not be converted to System.DateTime的解决方案

  1. 如下json格式提交到后台后报:

    The JSON value could not be converted to System.DateTime. Path: $.beginTime | LineNumber: 3 | BytePositionInLine: 33.
    {
      "beginTime": "2023-06-08T08:00:00"
    }
    造成这个错误的原因为程序无法正常解析该json, 主要是为了提升执行效率;System.Text.Json作为微软内置json处理,效率更高更快。
    那么这个微软官方的json会认识什么格式的时间值呢?它只认下面的格式:
    1
    2
    3
    {
      "beginTime": "2023-06-08T08:00:00"
    }
    年月日和时分秒之间加一个T就OK了
  2. 若你执意不想要这个T,我们可以将微软默认的Json解析换掉,换成NewtonsoftJson就可以了。
    public void ConfigureServices(IServiceCollection services)
    {
       services.AddControllers().AddNewtonsoftJson();
    }

     

  3. 当然如果是属性的方式,那么以上方式较麻烦,可以通过重写JsonConverter,实现属性上的正确解析
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /// <summary>
       /// 识别日期格式为:yyyy-MM-dd HH:mm:ss的json字符串
       /// </summary>
       public class DateTimeISO8601NoT : JsonConverter<DateTime>
       {
           private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
     
           public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
           {
               if (reader.TokenType == JsonTokenType.String && DateTime.TryParseExact(reader.GetString(), DateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateTime))
               {
                   return dateTime;
               }
     
               throw new JsonException($"Unable to convert '{reader.GetString()}' to {typeof(DateTime)}.");
           }
     
           public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
           {
               writer.WriteStringValue(value.ToString(DateTimeFormat));
           }
       }
     
       然后为属性打上:
       [JsonConverter(typeof(DateTimeISO8601NoT))]
       public DateTime BeginTime { get; set; }

      

 
posted @   红泥巴煮雪  阅读(1845)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示