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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With