JsonConvertOverride.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System.Text.Json;
  2. namespace OASystem.API.OAMethodLib
  3. {
  4. #region 日期格式转换("yyyy-MM-dd HH;mm:ss")
  5. public class DateTimeJsonConverter : System.Text.Json.Serialization.JsonConverter<DateTime>
  6. {
  7. private readonly string Format;
  8. public DateTimeJsonConverter(string format)
  9. {
  10. Format = format;
  11. }
  12. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  13. {
  14. if (string.IsNullOrEmpty(reader.GetString()))
  15. {
  16. return default(DateTime);
  17. }
  18. return DateTime.ParseExact(reader.GetString(), Format, null);
  19. }
  20. public override void Write(Utf8JsonWriter writer, DateTime date, JsonSerializerOptions options)
  21. {
  22. writer.WriteStringValue(date.ToString(Format));
  23. }
  24. //public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  25. //{
  26. // return DateTime.ParseExact(reader.GetString(), Format, null);
  27. //}
  28. }
  29. #endregion
  30. #region String null值转换(读/写)
  31. public class NullJsonConverter : System.Text.Json.Serialization.JsonConverter<string>
  32. {
  33. public override bool HandleNull => true;
  34. public override string Read(
  35. ref Utf8JsonReader reader,
  36. Type typeToConvert,
  37. JsonSerializerOptions options) =>
  38. reader.GetString() ?? "";
  39. public override void Write(
  40. Utf8JsonWriter writer,
  41. string value,
  42. JsonSerializerOptions options) =>
  43. writer.WriteStringValue(value ?? "");
  44. }
  45. #endregion
  46. #region decimal格式化 decimalPlaces=3 应用自定义的序列化器,并指定小数位数为 3
  47. public class DecimalConverter : System.Text.Json.Serialization.JsonConverter<decimal>
  48. {
  49. private readonly int decimalPlaces;
  50. public DecimalConverter(int decimalPlaces = 2)
  51. {
  52. this.decimalPlaces = decimalPlaces;
  53. }
  54. public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  55. {
  56. if (reader.TokenType == JsonTokenType.Number)
  57. return reader.GetDecimal();
  58. else
  59. throw new System.Text.Json.JsonException();
  60. }
  61. public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options)
  62. {
  63. string formatString = "0." + new string('0', decimalPlaces);
  64. string formattedValue = value.ToString(formatString); // 格式化字符串,保留指定位数的小数
  65. writer.WriteStringValue(formattedValue);
  66. }
  67. }
  68. #endregion
  69. }