35 lines
1.4 KiB
C#
35 lines
1.4 KiB
C#
|
using System.Text.Json;
|
|||
|
using System.Text.Json.Serialization;
|
|||
|
using Bunny.Dao.Common.Constant;
|
|||
|
|
|||
|
namespace Bunny.WebApi.Configuration;
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// 自定义Json转换器,用于将DateTime类型转换为JSON格式
|
|||
|
/// </summary>
|
|||
|
public class JsonDateTimeConverter : JsonConverter<DateTime>
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
/// 重写读取方法,将JSON数据转换为DateTime类型
|
|||
|
/// </summary>
|
|||
|
/// <param name="reader">JSON读取器</param>
|
|||
|
/// <param name="typeToConvert">要转换的目标类型</param>
|
|||
|
/// <param name="options">JSON序列化选项</param>
|
|||
|
/// <returns>转换后的DateTime对象</returns>
|
|||
|
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
|||
|
{
|
|||
|
return DateTime.TryParse(reader.GetString(), out var date) ? date : default;
|
|||
|
}
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// 重写写入方法,将DateTime对象转换为JSON格式并写入JSON写入器
|
|||
|
/// </summary>
|
|||
|
/// <param name="writer">JSON写入器</param>
|
|||
|
/// <param name="value">要写入的DateTime对象</param>
|
|||
|
/// <param name="options">JSON序列化选项</param>
|
|||
|
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
|
|||
|
{
|
|||
|
// 将DateTime对象转换为特定格式的字符串并写入JSON写入器
|
|||
|
writer.WriteStringValue(value.ToString(LocalDateTimeConstant.DefaultDateTimeSecondFormat));
|
|||
|
}
|
|||
|
}
|