如何从c#中的URL中检索JSON数据

时间:2017-04-29 04:51:52

标签: c# json

我正在尝试将JSON数据转换为C#类的对象,并将值显示到控制台程序中。每次运行时,我的控制台窗口都会显示为空白,我认为问题出在CurrencyRates类中,但我对此非常陌生并且不确定。任何帮助将不胜感激!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;



namespace Cooper_Lab12
{
    class Program
    {
        static void Main(string[] args)
        {


            var currencyRates = _download_serialized_json_data<CurrencyRates>("https://openexchangerates.org/api/latest.json?app_id=4be3cf28d6954df2b87bf1bb7c2ba47b");

            Console.Read();
        }


        private static T _download_serialized_json_data<T>(string url) where T : new()
        {


            //var currencyRates = _download_serialized_json_data<CurrencyRates>(url);
            using (var w = new WebClient())
            {

                var json_data = string.Empty;
                // attempt to download JSON data as a string
                try
                {
                    json_data = w.DownloadString("https://openexchangerates.org/api/latest.json?app_id=4be3cf28d6954df2b87bf1bb7c2ba47b ");
                }
                catch (Exception) { }
                // if string with JSON data is not empty, deserialize it to class and return its instance 
                return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
            }


        }
        public class RootObject
        {
            public string Disclaimer { get; set; }
            public string License { get; set; }
            public int Timestamp { get; set; }
            public string Base { get; set; }
            public Dictionary<string, decimal> Rates { get; set; }
        }

    }
}

这是我的CurrencyRates类:

public class CurrencyRates
{
    public string Disclaimer { get; set; }
    public string License { get; set; }
    public int TimeStamp { get; set; }
    public string Base { get; set; }
    public Dictionary<string, decimal> Rates { get; set; }
}

2 个答案:

答案 0 :(得分:3)

您的代码有效。但是,您不要尝试将结果输出到控制台。这就是你没有看到任何东西的原因。

如果您在Main之后的currencyRates方法中添加以下内容,则会看到已检索到的值。

Console.WriteLine($"{currencyRates.Disclaimer}");
Console.WriteLine($"{currencyRates.License}");
Console.WriteLine($"{currencyRates.TimeStamp}");
Console.WriteLine($"{currencyRates.Base}");
foreach (var currencyRatesRate in currencyRates.Rates)
{
    Console.WriteLine($"Key: {currencyRatesRate.Key}, Value: {currencyRatesRate.Value}");
}

备注

通常,您最好遵循标准命名约定,以便您的代码的读者快速赶上正在发生的事情。例如,所有方法名称都是用Pascal Case编写的。用于变量有意义的namings。对于instnace webClientw更有意义。变量名称写在Camel Case中。 E.g json_data应在jsonData中重命名。避免在代码中包含许多空行。代码的读者可以更容易地专注于几行并阅读您的代码。最后但并非最不重要的是,您为类型字符串的方法声明了一个参数,并且您从不使用它。应使用此参数代替DownloadString方法中的硬编码字符串。

您现在可以将重构的方法与我们最初的方法进行比较:

private static T DownloadAndDeserializeJsonData<T>(string url) where T : new()
{
    using (var webClient = new WebClient())
    {
        var jsonData = string.Empty;
        try
        {
            jsonData = webClient.DownloadString(url);
        }
        catch (Exception) { }
        return !string.IsNullOrEmpty(jsonData) 
                   ? JsonConvert.DeserializeObject<T>(jsonData) 
                   : new T();
    }
}

如果您想要一个关于.NET Framework和C#的命名指南的中心位置,您可以查看enter link description here

答案 1 :(得分:0)

我认为Microsoft的Http库对开发人员不是很友好,因此希望提出一种使用免费和开放源代码ServiceStack.Text库的替代方法,并且更容易实现上述目的。

    static void Main(string[] args)
    {
        // ret API url
        string url = "https://openexchangerates.org/api/latest.json?app_id=4be3cf28d6954df2b87bf1bb7c2ba47b";

        // GET Json data from api & map to CurrencyRates
        var todo =  url.GetJsonFromUrl().FromJson<CurrencyRates>();

        // print result to screen
        todo.PrintDump();
    }
    public class CurrencyRates
    {
        public string Disclaimer { get; set; }
        public string License { get; set; }
        public int TimeStamp { get; set; }
        public string Base { get; set; }
        public Dictionary<string, decimal> Rates { get; set; }
    }

这是一种从外部API获取数据的更加简洁/可读/可维护的方式。

您只需安装Nuget软件包ServiceStack.Text即可实现。通过运行

Install-Package ServiceStack.Text 

在您的NuGet Package控制台管理器中。

相关问题