Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimals to integer when deserializing JSON using Newtonsoft.Json

Tags:

.net

json.net

Is it possible to convert decimals to integer when deserializing JSON using Newtonsoft.Json?

Suddenly our service is receiving JSON data containing decimal values where int types are expected, example: 18483.0.

As a result exceptions are thrown like "Newtonsoft.Json.JsonReaderException: Input string '18483.0' is not a valid integer."

Obviously this specific property is defined as integer, and I prefer not to change it to some decimal type, but to convert the input to int, and stripping the decimals (which are always .0 anyway).

like image 865
George Avatar asked Jun 18 '26 09:06

George


1 Answers

You can have a custom generic JsonConverter like below :

public class CustomIntConverter : JsonConverter<int>
{
    public override void WriteJson(JsonWriter writer, int value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString());
    }

    public override int ReadJson(JsonReader reader, Type objectType, int existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        return Convert.ToInt32(reader.Value);
    }
}

It tries to cast it to an integer if it fails then it casts it to a double and then to an int. You can use it like below :

var json = @"{""B"":42.0}";
var result = JsonConvert.DeserializeObject<A>(json, new CustomIntConverter());

Fiddle

Edit Applied @vernou's suggestion

like image 129
Eldar Avatar answered Jun 20 '26 00:06

Eldar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!