George
George

Reputation: 1191

Convert decimals to integer when deserializing JSON using Newtonsoft.Json

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

Upvotes: 7

Views: 4811

Answers (2)

Serge
Serge

Reputation: 43860

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);
    }
}

Upvotes: 4

Eldar
Eldar

Reputation: 10790

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

Upvotes: 7

Related Questions