Home > Software design >  Convert decimals to integer when deserializing JSON using Newtonsoft.Json
Convert decimals to integer when deserializing JSON using Newtonsoft.Json

Time:09-21

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).

CodePudding user response:

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

CodePudding user response:

you can create a custom property converter

    var json = @"{ ""StringProperty"":""StringProperty"", ""IntProperty"":29.0}";

    var test = JsonConvert.DeserializeObject<Test>(json);

public class Test
{
    public string StringProperty { get; set; }

    [JsonConverter(typeof(DoubleToIntConverter))]
    public int IntProperty { get; set; }
}
    
public class DoubleToIntConverter : JsonConverter<int>
{
    public override void WriteJson(JsonWriter writer, int value, JsonSerializer serializer)
    {
        writer.WriteValue(value);
    }

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