JsonConvertOverride.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Newtonsoft.Json.Serialization;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace OASystem.API.OAMethodLib
  5. {
  6. #region 日期格式转换
  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 void Write(Utf8JsonWriter writer, DateTime date, JsonSerializerOptions options)
  15. {
  16. writer.WriteStringValue(date.ToString(Format));
  17. }
  18. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  19. {
  20. return DateTime.ParseExact(reader.GetString(), Format, null);
  21. }
  22. }
  23. #endregion
  24. #region String null值转换(读/写)
  25. public class NullJsonConverter : System.Text.Json.Serialization.JsonConverter<string>
  26. {
  27. public override bool HandleNull => true;
  28. public override string Read(
  29. ref Utf8JsonReader reader,
  30. Type typeToConvert,
  31. JsonSerializerOptions options) =>
  32. reader.GetString() ?? "";
  33. public override void Write(
  34. Utf8JsonWriter writer,
  35. string value,
  36. JsonSerializerOptions options) =>
  37. writer.WriteStringValue(value ?? "");
  38. }
  39. #endregion
  40. #region String null值转换(读/写)
  41. //public class Int32JsonConverter : System.Text.Json.Serialization.JsonConverter<int?>
  42. //{
  43. // private readonly string Format;
  44. // public Int32JsonConverter(string format)
  45. // {
  46. // Format = format;
  47. // }
  48. // public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options)
  49. // {
  50. // writer.WriteStringValue((value ?? 0).ToString());
  51. // }
  52. // public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  53. // {
  54. // return Convert.ToInt32(reader.GetString()) ?? 0;
  55. // }
  56. //}
  57. #endregion
  58. }