using System.Text.Json; namespace OASystem.API.OAMethodLib { #region 日期格式转换("yyyy-MM-dd HH;mm:ss") public class DateTimeJsonConverter : System.Text.Json.Serialization.JsonConverter { private readonly string Format; public DateTimeJsonConverter(string format) { Format = format; } public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (string.IsNullOrEmpty(reader.GetString())) { return default(DateTime); } return DateTime.ParseExact(reader.GetString(), Format, null); } public override void Write(Utf8JsonWriter writer, DateTime date, JsonSerializerOptions options) { writer.WriteStringValue(date.ToString(Format)); } //public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) //{ // return DateTime.ParseExact(reader.GetString(), Format, null); //} } #endregion #region String null值转换(读/写) public class NullJsonConverter : System.Text.Json.Serialization.JsonConverter { public override bool HandleNull => true; public override string Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.GetString() ?? ""; public override void Write( Utf8JsonWriter writer, string value, JsonSerializerOptions options) => writer.WriteStringValue(value ?? ""); } #endregion #region decimal格式化 decimalPlaces=3 应用自定义的序列化器,并指定小数位数为 3 public class DecimalConverter : System.Text.Json.Serialization.JsonConverter { private readonly int decimalPlaces; public DecimalConverter(int decimalPlaces = 2) { this.decimalPlaces = decimalPlaces; } public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Number) return reader.GetDecimal(); else throw new System.Text.Json.JsonException(); } public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options) { string formatString = "0." + new string('0', decimalPlaces); string formattedValue = value.ToString(formatString); // 格式化字符串,保留指定位数的小数 writer.WriteStringValue(formattedValue); } } #endregion }