参数类型与参数不匹配(datetime)

参数:

{

  dt:"2022-03-02 03:16:26"

}

接收:DateTime

message:"参数与参数类型不匹配"

 

有两种

第一种:

   第一步:自定义DateTime解析类

public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.TryParse(reader.GetString(), out var dateTime) ? dateTime : default(DateTime);
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
DateTime?类型解析类

public class DateTimeNullableConvert : JsonConverter<DateTime?>
{
public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.TryParse(reader.GetString(), out var dateTime) ? dateTime : default(DateTime?);
}

public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
{
writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
第二步:在startup中加入此两个类:

services.AddControllers().AddJsonOptions(config =>
{
//此设定解决JsonResult中文被编码的问题
config.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);

config.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
config.JsonSerializerOptions.Converters.Add(new DateTimeNullableConvert());
})

 

 

第二种比较简单

services.AddControllersWithViews()

    .AddNewtonsoftJson(options=>    {

        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //序列化时key为驼峰样式        options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;

        options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";

        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;//忽略循环引用    });

不过要安装类库
install-package Microsoft.AspNetCore.Mvc.NewtonsoftJson
 
不过一般项目框架中都会安装这个

 

posted @ 2022-05-18 16:31  Best丶zhaotf  阅读(263)  评论(0编辑  收藏  举报