/// <summary> /// 自定义数值类型序列化转换器 /// </summary> public class DecimalDigitsConvert : JsonConverter { //是否开启自定义反序列化,值为true时,反序列化时会走ReadJson方法,值为false时,不走ReadJson方法,而是默认的反序列化 public override bool CanRead => false; //是否开启自定义序列化,值为true时,序列化时会走WriteJson方法,值为false时,不走WriteJson方法,而是默认的序列化 public override bool CanWrite => true; /// <summary> /// 序列化后保留小数位数 /// </summary> public virtual int? Digits { get; private set; } /// <summary> /// 构造函数 /// </summary> public DecimalDigitsConvert() { } /// <summary> /// 构造函数 /// </summary> /// <param name="digits">序列化后保留小数位数</param> public DecimalDigitsConvert(int digits) { this.Digits = digits; } public override bool CanConvert(Type objectType) { return objectType == typeof(decimal) || objectType == typeof(Nullable<decimal>); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } /// <summary> /// 重载序列化方法 /// </summary> /// <param name="writer"></param> /// <param name="value"></param> /// <param name="serializer"></param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); } else { if (Digits.HasValue) { string.Format("{0:N" + Digits + "}", value); } else { writer.WriteValue(value.ToString()); } } } }View Code
标签:Digits,Convert,Newtonsoft,值为,Json,override,序列化,public,objectType From: https://www.cnblogs.com/5tomorrow/p/16745175.html