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 包。

     
     
  • 相关阅读:
    vue 购买弹出框 动画
    vue 和animate.css 的动画使用
    获得url地址?后的参数
    Java 实现随机数组元素升降序
    java for循环实现九九乘法表
    java 随机生成字符串验证码
    Mysql插入值时,避免重复插入
    Mysql的unique和primary key
    2020 3.6日电话面试(某外包公司)
    Intellij IDEA配置javaweb项目
  • 原文地址:https://www.cnblogs.com/puzi0315/p/13523420.html
Copyright © 2011-2022 走看看