关于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会认识什么格式的时间值呢?它只认下面的格式:
    {
      "beginTime": "2023-06-08T08:00:00"
    }
    年月日和时分秒之间加一个T就OK了
  2. 若你执意不想要这个T,我们可以将微软默认的Json解析换掉,换成NewtonsoftJson就可以了。
    public void ConfigureServices(IServiceCollection services)
    {
       services.AddControllers().AddNewtonsoftJson();
    }

     

  3. 当然如果是属性的方式,那么以上方式较麻烦,可以通过重写JsonConverter,实现属性上的正确解析
     /// <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 @ 2023-06-08 17:12  红泥巴煮雪  阅读(987)  评论(0编辑  收藏  举报