using System; using System.Text.Json; using System.Text.Json.Serialization; namespace Znyc.Recruitment.Admin.Commons.Helpers { /// /// 时间类型格式数据处理 /// public class DateTimeJsonConverter : JsonConverter { /// /// 时间格式 /// private readonly string _dateFormatString; /// /// public DateTimeJsonConverter() { _dateFormatString = "yyyy-MM-dd HH:mm:ss"; } /// /// /// 时间格式 public DateTimeJsonConverter(string dateFormatString) { _dateFormatString = dateFormatString; } /// /// /// /// /// /// public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { if (DateTime.TryParse(reader.GetString(), out DateTime date)) { return date; } } return reader.GetDateTime(); } /// /// /// /// /// public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss")); } } public class DateTimeNullableConverter : JsonConverter { public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return string.IsNullOrEmpty(reader.GetString()) ? default(DateTime?) : DateTime.Parse(reader.GetString()); } public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) { writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss")); } } }