菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
99
0

Asp.netCore 3.1 WebApi时间类型的格式一直报错The JSON value could not be converted to System.DateTime. 解决方案

原创
05/13 14:22
阅读数 14945

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

 
 

 

发表评论

0/200
99 点赞
0 评论
收藏