- 在 Startup.cs 文件中的 ConfigureServices 方法中添加 AddJsonOptions 的设置:
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new DateOnlyConverter());
});
- 创建一个自定义的 DateOnlyConverter 实现 JsonConverter 接口:
public class DateOnlyConverter : JsonConverter
{
private const string DateFormat = "yyyy-MM-dd";
public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var str = reader.GetString();
return DateOnly.ParseExact(str, DateFormat, CultureInfo.InvariantCulture);
}
public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString(DateFormat));
}
}
- 在定义 API 返回值的 Response 类型时,将 DateOnly 类型改为 string 类型:
public class MyResponse
{
public string Date { get; set; }
}
- 将返回的 DateOnly 类型属性转换为 string 类型:
var response = new MyResponse
{
Date = dateOnly.ToString("yyyy-MM-dd")
};