//创建一个类继承JsonConverter类
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace webapi
{
public class DataConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var strDate = reader.GetString();
if (!string.IsNullOrWhiteSpace(strDate) && !strDate.Contains(" "))
{
strDate += "00:00:00";
}
return DateTime.ParseExact(string.IsNullOrWhiteSpace(strDate) ? "1991-01-01" : strDate, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture);
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
}
}
}
//如果在webapi里使用可以注入到服务
builder.Services.AddControllers().AddJsonOptions(options =>
{
// 忽略循环序列化
options.JsonSerializerOptions.ReferenceHandler=ReferenceHandler.IgnoreCycles;
// 时间转换
options.JsonSerializerOptions.Converters.Add(new DataConverter());
});