简体   繁体   English

如何在c#中访问反序列化的Json对象的各个元素?

[英]How to access the individual elements of a deserialized Json object in c#?

I am writing a program to access the currency data from the http://api.fixer.io/latest?base=INR . 我正在编写一个程序,以从http://api.fixer.io/latest?base=INR访问货币数据。 I am able to get the json data, desreialize it and move it to a var obj. 我能够获取json数据,对其进行反序列化并将其移至var obj。

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

Now I want to access all the rates in obj, ie the currency code and the currency value in separate fields and update SQL. 现在,我想访问obj中的所有费率,即单独字段中的货币代码和货币值并更新SQL。 I am not sure how to use foreach or for loop on obj. 我不确定如何在obj上使用foreach或for循环。

I tried using the following code but it gives error in the 2nd foreach loop. 我尝试使用以下代码,但在第二个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);
        }
    }
}

You don't need the second foreach. 您不需要第二个foreach。

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

You have already found the currency you want. 您已经找到了想要的货币。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM