簡體   English   中英

將字典轉換為 Json 並返回時出現意外錯誤

[英]Unexpected error in converting dictionary to Json & back

在下面的代碼中,我收到錯誤:

{"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

任何想法為什么會發生這種情況? 我怎樣才能避免錯誤?

該字典還包含其他類型,已被省略。

您可以編寫一個轉換器 function 轉換為 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);
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM