2015-05-21 24 views
0

我正在編寫程序以訪問http://api.fixer.io/latest?base=INR的貨幣數據。我能夠獲取json數據,解除它並將其移動到var obj。如何訪問c#中的反序列化Json對象的單個元素?

var obj = js.Deserialize<dynamic>(json); 

現在我想要訪問obj中的所有費率,即貨幣代碼和貨幣值在單獨的字段中並更新SQL。我不知道如何使用foreach或for obj循環。

我嘗試使用下面的代碼,但它在第二個foreach循環中給出錯誤。

foreach (KeyValuePair<string, object> currency in obj) 
{ 
    if (currency.Key == "rates") 
    { 
     foreach(KeyValuePair<string, double> i in currency.Value) 
     { 
      Console.WriteLine("{0} : {1}", currency.Key, currency.Value); 
     } 
    } 
} 

回答

1

你不需要第二個foreach。

foreach (KeyValuePair<string, object> currency in obj) 
{ 
    if (currency.Key == "rates") 
    { 
     Console.WriteLine("{0} : {1}", currency.Key, currency.Value); 
    } 
} 

您已經找到想要的貨幣。

+0

第一個循環只給我 – Manoj

+0

在這種情況下,它返回率:System.Collections.Generic.Dictionary'2 [System.String.System.Object]。有31種我需要訪問的貨幣。 – Manoj