C# 将字典转换为Json时出现意外错误&;返回
在下面的代码中,我收到了错误:C# 将字典转换为Json时出现意外错误&;返回,c#,json.net,C#,Json.net,在下面的代码中,我收到了错误: {"Unable to cast object of type 'System.Int64' to type 'System.Int32'."} 代码如下: var dic = new Dictionary<string, object>() { { "value", 100 } }; var json = JsonConvert.SerializeObject(dic); dic = JsonConvert.DeserializeObject<
{"Unable to cast object of type 'System.Int64' to type 'System.Int32'."}
代码如下:
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
var dic=newdictionary(){{“value”,100};
var json=JsonConvert.SerializeObject(dic);
dic=JsonConvert.DeserializeObject(json);
int值=(int)dic[“值”]//在这里抛出错误
你知道为什么会这样吗?
我怎样才能避免这个错误
字典还包含其他类型,这些类型已被省略。您可以编写一个转换函数,将其转换为int32并捕获超出范围的错误:
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);
}
intgetasint(对象值)
{
if(value.GetType()!=typeof(Int64))
{
抛出新的异常(“某物”);
}
var i64=(Int64)值;
if(i64Int32.MaxValue)
{
抛出新ArgumentOutOfRangeException(“废话”);
}
返回Convert.ToInt32(i64);
}
为什么dictionary对象的值是
?如果您知道它是一个int,那么将它设为int。这是一个示例,字典也将包含其他类型。好的,但是反序列化时,反序列化程序不知道该值的范围,因此选择可能的最大整数类型(int64)。如果该字段可以包含不同的类型,那么我建议您使用JsonConverter根据您创建的规则而不是自动规则来“正确”解释值。我建议看看我昨天贴在一张非常类似的便条上的答案:我明白问题所在,谢谢。