0

In the code below I am receiving the error:

{"Unable to cast object of type 'System.Int64' to type 'System.Int32'."}

Here is the code:

var dic = new Dictionary<string, object>() { { "value", 100 } };
var json = JsonConvert.SerializeObject(dic);
dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
int value = (int)dic["value"];//throws error here

Any ideas why this should happen? How can i avoid the error?

The dictionary contains other types too which have been omitted.

Paul Stanley
  • 1,999
  • 1
  • 22
  • 60
  • Why is the value of the dictionary `object`? If you know it's an int, then make it an int. – Neil May 12 '20 at 09:39
  • It is an example the dictionary will contain other types too. – Paul Stanley May 12 '20 at 09:40
  • 2
    OK, but when deserialising, the deserialiser has no idea of the range of that value, so chooses the biggest possible integer type (int64). If that field can contain different types, then I suggest you use a JsonConverter to interpret the values 'correctly' based on rules you create, rather than automatic ones. I suggest looking at the answer I posted yesterday on a very similar note: https://stackoverflow.com/questions/61734655/c-sharp-convert-json-to-object-with-duplicated-property-name-with-different-data/61735026#61735026 – Neil May 12 '20 at 09:42
  • I see the problem thanks. – Paul Stanley May 12 '20 at 09:53

1 Answers1

1

You could write a converter function that converts to int32 and traps for out of range errors:

int GetAsInt(object value)
{
    if(value.GetType() != typeof(Int64))
    {
        throw new ArgumentException("something");
    }
    var i64 = (Int64)value;
    if(i64 < Int32.MinValue || i64 > Int32.MaxValue)
    {
        throw new ArgumentOutOfRangeException("blah");
    }
    return Convert.ToInt32(i64);
 }
Neil
  • 11,059
  • 3
  • 31
  • 56