using Newtonsoft.Json.Serialization; using System.Text.Json; using System.Text.Json.Serialization; namespace OASystem.API.OAMethodLib { #region 日期格式转换 public class DateTimeJsonConverter : System.Text.Json.Serialization.JsonConverter { private readonly string Format; public DateTimeJsonConverter(string format) { Format = format; } 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 null值转空字符串 NewtonsoftJson public class NullToEmptyStringResolver : CamelCasePropertyNamesContractResolver { /// /// 创建属性 /// /// 类型 /// 序列化成员 /// protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) { return type.GetProperties().Select(c => { var jsonProperty = base.CreateProperty(c, memberSerialization); jsonProperty.ValueProvider = new NullToEmptyStringValueProvider(c); return jsonProperty; }).ToList(); } } public class NullToEmptyStringValueProvider : IValueProvider { private readonly PropertyInfo _memberInfo; /// /// 构造函数 /// /// public NullToEmptyStringValueProvider(PropertyInfo memberInfo) { _memberInfo = memberInfo; } /// /// 获取Value /// /// /// public object GetValue(object target) { var result = _memberInfo.GetValue(target); if (_memberInfo.PropertyType == typeof(string) && result == null) result = string.Empty; return result; } /// /// 设置Value /// /// /// public void SetValue(object target, object value) { _memberInfo.SetValue(target, value); } } #endregion }