定义一个继承System.Text.Json.Serialization.JsonConverter的类,实现其Read 和 Write两个抽象方法;DateTimeFormat 设置返回的日期格式
/// <summary>
/// JSON 返回日期格式格式化
/// </summary>
public class DateTimeConverter : JsonConverter<DateTime>
{
public string DateTimeFormat { get; set; } = "yyyy-MM-dd";
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => DateTime.Parse(reader.GetString());
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString(this.DateTimeFormat));
}
然后在Startup.cs中的ConfigureServices添加代码
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0).AddJsonOptions(json => {
//统一设置JsonResult中的日期格式
json.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});