Paul Stanley
Paul Stanley

Reputation: 2161

Unexpected error in converting dictionary to Json & back

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.

Upvotes: 0

Views: 98

Answers (1)

Neil
Neil

Reputation: 11889

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

Upvotes: 1

Related Questions