1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- using System.Text.Json;
- namespace OASystem.API.OAMethodLib
- {
- #region 日期格式转换("yyyy-MM-dd HH;mm:ss")
- public class DateTimeJsonConverter : System.Text.Json.Serialization.JsonConverter<DateTime>
- {
- 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<string>
- {
- 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<decimal>
- {
- 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
- }
|