zoukankan      html  css  js  c++  java
  • Asp.netCore 3.1 WebApi时间类型的格式一直报错The JSON value could not be converted to System.DateTime. 解决方案

    在用Asp.netCore 3.1 开发 WebApi 接口,若有时间类型的字段,会经常一个错误。

    入参:

    {
      "schoolId": 111,
      "beginTime": "2020-08-18 08:00:00",
      "endTime": "2020-08-18 10:00:00",
    
    }

    然后就会报错:

    The JSON value could not be converted to System.DateTime. Path: $.beginTime | LineNumber: 0 | BytePositionInLine: 48.
    {
      "code": 400,
      "msg": "The JSON value could not be converted to System.DateTime. Path: $.beginTime | LineNumber: 0 | BytePositionInLine: 48."
    }

    为啥会有这个错误?时间格式明明没问题啊。

    原因为程序无法正常解析该json, 主要是为了提升执行效率;System.Text.Json作为微软内置json处理,效率更高更快。

    那么这个微软官方的json会认识什么格式的时间值呢?它只认下面的格式

    2020-08-18T08:00  
    年月日和时分秒之间加一个T就OK了。
     
    当然,还有一个解决方案,若你执意不想要这个T,我们可以将微软默认的Json解析换掉,换成NewtonsoftJson就可以了。
    为Controllers添加NewtonsoftJson注册,在Startup.cs下
    public void ConfigureServices(IServiceCollection services)
    {
       services.AddControllers() .AddNewtonsoftJson();
    }

    需要安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包。

     
     
  • 相关阅读:
    php单点登录
    【Docker】docker镜像构建
    【测试经验】网关中间件测试
    【Jmeter】调用Dubbo方法
    【计算机网络】TCP三次握手与四次挥手
    【操作系统】死锁
    【操作系统】线程与进程
    【计算机网络】TCP/IP
    【计算机网络】Http与Https
    【二叉树】二叉树的创建与遍历
  • 原文地址:https://www.cnblogs.com/puzi0315/p/13523420.html
Copyright © 2011-2022 走看看