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