JsonConverterUtil.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace Util
  5. {
  6. public class JsonConverterUtil
  7. {
  8. public class DateTimeNullConverter : JsonConverter<DateTime?>
  9. {
  10. public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  11. => string.IsNullOrEmpty(reader.GetString()) ? default : ParseDateTime(reader.GetString());
  12. public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
  13. => writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss"));
  14. }
  15. public class DateTimeConverter : JsonConverter<DateTime>
  16. {
  17. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  18. {
  19. var dateTime = ParseDateTime(reader.GetString());
  20. return dateTime == null ? DateTime.MinValue : dateTime.Value;
  21. }
  22. public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
  23. => writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
  24. }
  25. public static DateTime? ParseDateTime(string dateStr)
  26. {
  27. if (System.Text.RegularExpressions.Regex.IsMatch(dateStr, @"^\d{4}[/-]") && DateTime.TryParse(dateStr, null, System.Globalization.DateTimeStyles.AssumeLocal, out var dateVal))
  28. return dateVal;
  29. return null;
  30. }
  31. }
  32. }