• 欢迎光临~

关于去掉decimal 数据尾部无效0的JsonConverter写法

开发技术 开发技术 2022-06-10 次浏览

转json 可用, 转datatable 还在调试中

 public class DecimalCoverterUselessZero : JsonConverter
    {
        private void dumpNumArray<T>(JsonWriter writer, T n)
        {
            var s = n.ToString();
            if (s.EndsWith(".0"))
                writer.WriteRawValue(s.Substring(0, s.Length - 2));
            else if (s.Contains("."))
                writer.WriteRawValue(s.TrimEnd('0').TrimEnd('.'));
            else
                writer.WriteRawValue(s);
        }
        public override void WriteJson(JsonWriter writer, object value,
           JsonSerializer serializer)
        {
            Type t = value.GetType();
            if (t == dblArrayType)
                dumpNumArray<double>(writer, (double)value);
            else if (t == decArrayType)
                dumpNumArray<decimal>(writer, (decimal)value);
            else
                throw new NotImplementedException();
        }
        private Type dblArrayType = typeof(double);
        private Type decArrayType = typeof(decimal);
        public override bool CanConvert(Type objectType)
        {
            if (objectType == dblArrayType || objectType == decArrayType)
                return true;
            return false;
        }
        public override bool CanRead
        {
            get { return false; }
        }
        public override object ReadJson(JsonReader reader, Type objectType,
            object existingValue, JsonSerializer serializer)
        {
           // var it = (long)reader.Value;

            throw new NotImplementedException();
        }
    

    }

属性 特性

 [JsonConverter(typeof(DecimalCoverterUselessZero))]
        public decimal? DailyRent { get; set; }

sqlsugar 

}).ToJson();  是确实转了,可我想要转成datatable

其他测试

   JsonSerializerSettings s1 = new JsonSerializerSettings();
            s1.Converters.Add(new DecimalCoverterUselessZero());  

          var  test  = JsonConvert.SerializeObject(12.3600000, null, s1);    

 

程序员灯塔
转载请注明原文链接:关于去掉decimal 数据尾部无效0的JsonConverter写法
喜欢 (0)