2015-05-21 17 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