Handling decimal values in Newtonsoft.Json

后端 未结 3 995
日久生厌
日久生厌 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:21

    You can handle both formats (the JSON number representation and the masked string format) using a custom JsonConverter class like this.

    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)
        {
            JToken token = JToken.Load(reader);
            if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer)
            {
                return token.ToObject();
            }
            if (token.Type == JTokenType.String)
            {
                // customize this to suit your needs
                return Decimal.Parse(token.ToString(), 
                       System.Globalization.CultureInfo.GetCultureInfo("es-ES"));
            }
            if (token.Type == JTokenType.Null && objectType == typeof(decimal?))
            {
                return null;
            }
            throw new JsonSerializationException("Unexpected token type: " + 
                                                  token.Type.ToString());
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

    To plug this into your binder, just add an instance of the converter to the Converters list in the JsonSerializerSettings object:

    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore,
        MissingMemberHandling = MissingMemberHandling.Ignore,
        Formatting = Formatting.None,
        DateFormatHandling = DateFormatHandling.IsoDateFormat,
        Converters = new List { new DecimalConverter() }
    };
    

提交回复
热议问题