Handling decimal values in Newtonsoft.Json

后端 未结 3 997
日久生厌
日久生厌 2020-11-28 08:04

Edit: It\'s been almost 5 years and I don\'t think this is the way to go. The client should post the data in the correct numerical format. With current fram

3条回答
  •  时光说笑
    2020-11-28 08:27

    Thanx a lot! I was looking for a solution to make decimals always serialize in a similar manner and this post sent me in the right direction. This is my code:

        internal class DecimalConverter : JsonConverter
        {
            public override bool CanConvert(Type objectType)
            {
                return (objectType == typeof(decimal) || objectType == typeof(decimal?));
            }
    
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                throw new NotImplementedException();
            }
    
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                Decimal? d = default(Decimal?);
                if (value != null)
                {
                    d = value as Decimal?;
                    if (d.HasValue) // If value was a decimal?, then this is possible
                    {
                        d = new Decimal?(new Decimal(Decimal.ToDouble(d.Value))); // The ToDouble-conversion removes all unnessecary precision
                    }
                }
                JToken.FromObject(d).WriteTo(writer);
            }
        }
    

提交回复
热议问题