I am trying to convert JSON data into objects of a C# class and display the values into a console program. My console window comes up blank each time I run it, I believe the problem is within CurrencyRates class but I am very new to this and unsure. Any help would be appreciated!!
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; }
}
}
}
and here is my CurrencyRates class:
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; }
}
Console.Write(currencyRates)within yourMainfunction?_download_serialized_json_dataactually returns a de-serialized object. You can loop over theRatesproperty and write to the console as the user Christos suggested in the answer.