关于The JSON value could not be converted to System.DateTime的解决方案
-
如下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会认识什么格式的时间值呢?它只认下面的格式:123{
"beginTime"
:
"2023-06-08T08:00:00"
}
年月日和时分秒之间加一个T就OK了 -
若你执意不想要这个T,我们可以将微软默认的Json解析换掉,换成NewtonsoftJson就可以了。
public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(); }
- 当然如果是属性的方式,那么以上方式较麻烦,可以通过重写JsonConverter,实现属性上的正确解析
1234567891011121314151617181920212223242526
/// <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
; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了