JsonConvertOverride.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using Newtonsoft.Json;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace OASystem.API.OAMethodLib
  5. {
  6. #region 日期格式转换("yyyy-MM-dd HH;mm:ss")
  7. public class DateTimeJsonConverter : System.Text.Json.Serialization.JsonConverter<DateTime>
  8. {
  9. private readonly string Format;
  10. public DateTimeJsonConverter(string format)
  11. {
  12. Format = format;
  13. }
  14. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  15. {
  16. if (string.IsNullOrEmpty(reader.GetString()))
  17. {
  18. return default(DateTime);
  19. }
  20. return DateTime.ParseExact(reader.GetString(), Format, null);
  21. }
  22. public override void Write(Utf8JsonWriter writer, DateTime date, JsonSerializerOptions options)
  23. {
  24. writer.WriteStringValue(date.ToString(Format));
  25. }
  26. //public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  27. //{
  28. // return DateTime.ParseExact(reader.GetString(), Format, null);
  29. //}
  30. }
  31. #endregion
  32. #region String null值转换(读/写)
  33. public class NullJsonConverter : System.Text.Json.Serialization.JsonConverter<string>
  34. {
  35. public override bool HandleNull => true;
  36. public override string Read(
  37. ref Utf8JsonReader reader,
  38. Type typeToConvert,
  39. JsonSerializerOptions options) =>
  40. reader.GetString() ?? "";
  41. public override void Write(
  42. Utf8JsonWriter writer,
  43. string value,
  44. JsonSerializerOptions options) =>
  45. writer.WriteStringValue(value ?? "");
  46. }
  47. #endregion
  48. #region decimal格式化
  49. #endregion
  50. }