Not sure why Open Weather API C# Call is not working - c#

I am having difficulty replacing the Dark Sky API with Open weather. GPS Location works and is received through another azure function.The Dark Sky Api call still works too. It might be something little but I'm not sure what's wrong. The only significant difference from the Dark Sky Api is the data model. Yet, Postman keeps responding with null values.
Postman response:
{
"id": 0,
"main": null,
"description": null,
"icon": null
}
public interface IWeatherService
{
Task<Weather> GetWeatherAsync(double latitude, double longitude);
}
public class WeatherService : IWeatherService
{
private readonly HttpClient _client;
private readonly ILogger<IWeatherService> _logger;
public WeatherService(HttpClient client, ILogger<IWeatherService> logger)
{
_client = client;
_client.BaseAddress = new Uri("https://api.openweathermap.org/data/2.5/weather?");
_client.Timeout = TimeSpan.FromSeconds(10);
_logger = logger;
}
public async Task<Weather> GetWeatherAsync(double latitude, double longitude)
{
Weather retval = null;
try
{
if (latitude.Equals(0) || longitude.Equals(0))
return null;
var key = "HIDDEN";
// var API = Environment.GetEnvironmentVariable("WeatherKey");
var exclude = "minutely,hourly,daily,alerts";
var units = "imperial";
var requestUrl = $"&lat={latitude}&lon={longitude}&exclude={exclude}&units={units}&appid={key}";
var response = await _client.GetAsync(requestUrl);
var result = response.Content.ReadAsStringAsync().Result;
var weather = JsonConvert.DeserializeObject<Weather>(result);
retval = weather;
//}
//handler.Dispose();
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error in {nameof(GetWeatherAsync)}");
}
return retval;
}
The new model:
namespace WeatherWebAPI.Models
{
using Newtonsoft.Json;yy
public partial class Temperatures
{
[JsonProperty("coord")]
public Coord Coord { get; set; }
[JsonProperty("weather")]
public Weather[] Weather { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("main")]
public Main Main { get; set; }
[JsonProperty("visibility")]
public long Visibility { get; set; }
[JsonProperty("wind")]
public Wind Wind { get; set; }
[JsonProperty("clouds")]
public Clouds Clouds { get; set; }
[JsonProperty("dt")]
public long Dt { get; set; }
[JsonProperty("sys")]
public Sys Sys { get; set; }
[JsonProperty("timezone")]
public long Timezone { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("cod")]
public long Cod { get; set; }
}
public partial class Clouds
{
[JsonProperty("all")]
public long All { get; set; }
}
public partial class Coord
{
[JsonProperty("lon")]
public double Lon { get; set; }
[JsonProperty("lat")]
public double Lat { get; set; }
}
public partial class Main
{
[JsonProperty("temp")]
public double Temp { get; set; }
[JsonProperty("feels_like")]
public double FeelsLike { get; set; }
[JsonProperty("temp_min")]
public double TempMin { get; set; }
[JsonProperty("temp_max")]
public double TempMax { get; set; }
[JsonProperty("pressure")]
public long Pressure { get; set; }
[JsonProperty("humidity")]
public long Humidity { get; set; }
}
public partial class Sys
{
[JsonProperty("type")]
public long Type { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("message")]
public double Message { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("sunrise")]
public long Sunrise { get; set; }
[JsonProperty("sunset")]
public long Sunset { get; set; }
}
public partial class Weather
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("main")]
public string Main { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
}
public partial class Wind
{
[JsonProperty("speed")]
public double Speed { get; set; }
[JsonProperty("deg")]
public long Deg { get; set; }
}
}
The Old Model:
namespace WeatherWebAPI.Models
{
#pragma warning disable IDE1006 // Naming Styles
public class Response
{
public double latitude { get; set; }
public double longitude { get; set; }
public string timezone { get; set; }
public DataPoint currently { get; set; }
}
public class DataPoint
{
public double apparentTemperatureHigh { get; set; }
public string apparentTemperatureHighTime { get; set; }
public double apparentTemperatureLow { get; set; }
public string apparentTemperatureLowTime { get; set; }
public double apparentTemperatureMax { get; set; }
public string apparentTemperatureMaxTime { get; set; }
public double apparentTemperatureMin { get; set; }
public string apparentTemperatureMinTime { get; set; }
public long time { get; set; }
public string summary { get; set; }
public string icon { get; set; }
public string sunriseTime { get; set; }
public string sunsetTime { get; set; }
public double nearestStormDistance { get; set; }
public double nearestStormBearing { get; set; }
public double precipIntensity { get; set; }
public double precipIntensityMax { get; set; }
public string precipIntensityMaxTime { get; set; }
public string precipIntensityError { get; set; }
public double preciProbability { get; set; }
public string precipType { get; set; }
public double temperature { get; set; }
public double temperatureHigh { get; set; }
public string temperatureHighTime { get; set; }
public double temperatureLow { get; set; }
public string temperatureLowTime { get; set; }
public double temperatureMax { get; set; }
public string temperatureMaxTime { get; set; }
public double temperatureMin { get; set; }
public string temperatureMinTime { get; set; }
public double apparentTemperature { get; set; }
public double dewPoint { get; set; }
public double humidity { get; set; }
public double pressure { get; set; }
public double windSpeed { get; set; }
public double windGust { get; set; }
public string windGustTime { get; set; }
public double windBearing { get; set; }
public double cloudCover { get; set; }
public double uvIndex { get; set; }
public double uvIndexTime { get; set; }
public double visibility { get; set; }
public double ozone { get; set; }
public double moonPhase { get; set; }
}
#pragma warning restore IDE1006 // Naming Styles
}

Related

Using Json.net to deserialize Json with some changing object names

I'm new here so thanks for the great content; invaluable stuff.
I'm deserializing some Json from TDAmeritrade into a C# desktop app using the "Option Chain" api.
Depending on the input to the api, I can get a response with multiple expiration dates, multiple strike prices, and multiple option objects.
Here's a link to a typical response: API ResponseTDAmeritrade Json Example
A snippet of the problem code:
"numberOfContracts": 8,
"putExpDateMap": {
**"2020-08-21:50": {
"15.0":** [
{
"putCall": "PUT",
"symbol": "FMCI_082120P15",
"description": "FMCI Aug 21 2020 15 Put",
"exchangeName": "OPR",
The problem is that the dates and strike prices change in each response. I've learned that I can deserialize into a "Dictionary<string, List<Type> listName" so I did that in the OptionChain and ExpDate classes but still can't get it working.
Here is the current error: error trace
Here are my classes, created from json2csharp.com but with the date and strike price classes modified:
class OptionChain
{
public string symbol { get; set; }
public string status { get; set; }
public Underlying underlying { get; set; }
public string strategy { get; set; }
public double interval { get; set; }
public bool isDelayed { get; set; }
public bool isIndex { get; set; }
public double interestRate { get; set; }
public double underlyingPrice { get; set; }
public double volatility { get; set; }
public double daysToExpiration { get; set; }
public int numberOfContracts { get; set; }
public Dictionary<string, List<expDate>> putExpDateMap { get; set; }
public Dictionary<string, List<expDate>> callExpDateMap { get; set; }
public class expDate
{
public Dictionary<string, List<StrikePrice>> strikePrices { get; set; }
}
public class StrikePrice
{
public Option[] options { get; set; }
}
public class Option
{
public string putCall { get; set; }
public string symbol { get; set; }
public string description { get; set; }
public string exchangeName { get; set; }
public double bid { get; set; }
public double ask { get; set; }
public double last { get; set; }
public double mark { get; set; }
public int bidSize { get; set; }
public int askSize { get; set; }
public string bidAskSize { get; set; }
public int lastSize { get; set; }
public double highPrice { get; set; }
public double lowPrice { get; set; }
public double openPrice { get; set; }
public double closePrice { get; set; }
public int totalVolume { get; set; }
public object tradeDate { get; set; }
public long tradeTimeInLong { get; set; }
public long quoteTimeInLong { get; set; }
public double netChange { get; set; }
public double volatility { get; set; }
public double delta { get; set; }
public double gamma { get; set; }
public double theta { get; set; }
public double vega { get; set; }
public double rho { get; set; }
public int openInterest { get; set; }
public double timeValue { get; set; }
public double theoreticalOptionValue { get; set; }
public double theoreticalVolatility { get; set; }
public OptionDeliverablesList optionDeliverablesList { get; set; }
public double strikePrice { get; set; }
public long expirationDate { get; set; }
public int daysToExpiration { get; set; }
public string expirationType { get; set; }
public long lastTradingDay { get; set; }
public double multiplier { get; set; }
public string settlementType { get; set; }
public string deliverableNote { get; set; }
public bool isIndexOption { get; set; }
public double percentChange { get; set; }
public double markChange { get; set; }
public double markPercentChange { get; set; }
public bool inTheMoney { get; set; }
public bool mini { get; set; }
public bool nonStandard { get; set; }
public class OptionDeliverablesList
{
public string symbol { get; set; }
public string assetType { get; set; }
public double deliverableUnits { get; set; }
public string currencyType { get; set; }
}
Am I doing something wrong in the Dictionaries? The way I understand it from my many hours of reading, the expiration dates and strike prices need to be read anonymously.
Thanks a bunch!
If I get your problem right - you have probelms deserializing json structure where keys are dynamic values but not static property names, correct? If so- you have modeled incorrect POCO (there are two nested dictionaries).
POCOs below give correct deserialization results (rest of properties skipped)
class OptionChain
{
public string Symbol { get; set; }
public string Status { get; set; }
public Dictionary<string, Dictionary<string, ExpDate[]>> PutExpDateMap { get; set; }
public Dictionary<string, Dictionary<string, ExpDate[]>> CallExpDateMap { get; set; }
//other properties ignored because dont matter
}
class ExpDate
{
public string ExchangeName { get; set; }
public decimal Bid { get; set; }
public decimal Ask { get; set; }
//other properties ignored because dont matter
}
Tested POCOs with json sample provided in your post:
static void Main(string[] args)
{
var t = File.ReadAllText("test.json");
var r = JsonConvert.DeserializeObject<OptionChain>(t);
Console.WriteLine($"Total elements in {nameof(r.PutExpDateMap)} : {r.PutExpDateMap.Count()}");
Console.WriteLine($"Keys in {nameof(r.PutExpDateMap)} : {string.Join(",", r.PutExpDateMap.Keys)}");
Console.WriteLine($"Total elements in {nameof(r.CallExpDateMap)} : {r.CallExpDateMap.Count()}");
Console.WriteLine($"Keys in {nameof(r.CallExpDateMap)} : {string.Join(",", r.CallExpDateMap.Keys)}");
}
Application output is:

Grabbing Json Data to String in Gridview

I'm setting up a website ASPX file that grabs the weather for the next 3 days, the output is in JSON and their classes are too complicated for me to understand it. If I want to extract just the weather for the next 3 days how do I go on about doing that?
https://samples.openweathermap.org/data/2.5/forecast?q=London,us&appid=b6907d289e10d714a6e88b30761fae22
This is the JSON output displayed on top.
What I'm trying to accomplish is to extract the next 3 days of the weather "Description" and put it to a GridView. I have used a JSON beautifier to get the classes but I am still confused.
Any help would be appreciated
This is my current code and I'm stuck here
protected void Button1_Click(object sender, EventArgs e)
{
string searchTerm = TextBox1.Text;
var webRequest = (HttpWebRequest)WebRequest.Create("https://samples.openweathermap.org/data/2.5/forecast?q=" + Server.UrlEncode(searchTerm) + "&units=metric&APPID=b6907d289e10d714a6e88b30761fae22");
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK)
{
Label1.Text = "The Next 3 days of weather in your area in" + searchTerm + " .";
JavaScriptSerializer json = new JavaScriptSerializer();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string resString = sr.ReadToEnd();
});
GridView1.DataSource = ?;
GridView1.DataBind();
}
else
Label.Text = "Invalid Response";
}
public class Main
{
public double temp { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
public double pressure { get; set; }
public double sea_level { get; set; }
public double grnd_level { get; set; }
public int humidity { get; set; }
public double temp_kf { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Sys
{
public string pod { get; set; }
}
public class Rain
{
public double __invalid_name__3h { get;
set; }
}
public class Snow
{
public double __invalid_name__3h { get;
set; }
}
public class List
{
public int dt { get; set; }
public Main main { get; set; }
public List<Weather> weather { get; set; }
public Clouds clouds { get; set; }
public Wind wind { get; set; }
public Sys sys { get; set; }
public string dt_txt { get; set; }
public Rain rain { get; set; }
public Snow snow { get; set; }
}
public class Coord
{
public double lat { get; set; }
public double lon { get; set; }
}
public class City
{
public int id { get; set; }
public string name { get; set; }
public Coord coord { get; set; }
public string country { get; set; }
}
public class RootObject
{
public string cod { get; set; }
public double message { get; set; }
public int cnt { get; set; }
public List<List> list { get; set; }
public City city { get; set; }
}

How to take elements from JSON from web service in C# console application to make exchange office?

I am new at programming and I try to make exchange office in C# console application. I use free API service for current currency rates. On this way i can read all API elements, but i don't know how to take elements what i need? For example i need to take USDEUR rate. How to do that?
My code is
string url = #"http://apilayer.net/api/live? access_key=8efc5a54419e913b695f694bbef4d97f& currencies = EUR,GBP,CAD,PLN& source = USD& format = 1";
string objects = new WebClient().DownloadString(url);
var lista = JsonConvert.SerializeObject(objects, Formatting.Indented);
var finish = lista.ToArray();
Console.WriteLine(finish);
You need to let JSON string be object.
There are two way you can make it
use JsonConvert.DeserializeObject method to get model.
Make a model
public class Quotes
{
public double USDAED { get; set; }
public double USDAFN { get; set; }
public double USDALL { get; set; }
public double USDAMD { get; set; }
public double USDANG { get; set; }
public double USDAOA { get; set; }
public double USDARS { get; set; }
public double USDAUD { get; set; }
public double USDAWG { get; set; }
public double USDAZN { get; set; }
public double USDBAM { get; set; }
public int USDBBD { get; set; }
public double USDBDT { get; set; }
public double USDBGN { get; set; }
public double USDBHD { get; set; }
public double USDBIF { get; set; }
public int USDBMD { get; set; }
public double USDBND { get; set; }
public double USDBOB { get; set; }
public double USDBRL { get; set; }
public int USDBSD { get; set; }
public double USDBTC { get; set; }
public double USDBTN { get; set; }
public double USDBWP { get; set; }
public double USDBYN { get; set; }
public int USDBYR { get; set; }
public double USDBZD { get; set; }
public double USDCAD { get; set; }
public double USDCDF { get; set; }
public double USDCHF { get; set; }
public double USDCLF { get; set; }
public double USDCLP { get; set; }
public double USDCNY { get; set; }
public double USDCOP { get; set; }
public double USDCRC { get; set; }
public int USDCUC { get; set; }
public double USDCUP { get; set; }
public double USDCVE { get; set; }
public double USDCZK { get; set; }
public double USDDJF { get; set; }
public double USDDKK { get; set; }
public double USDDOP { get; set; }
public double USDDZD { get; set; }
public double USDEGP { get; set; }
public double USDERN { get; set; }
public double USDETB { get; set; }
public double USDEUR { get; set; }
public double USDFJD { get; set; }
public double USDFKP { get; set; }
public double USDGBP { get; set; }
public double USDGEL { get; set; }
public double USDGGP { get; set; }
public double USDGHS { get; set; }
public double USDGIP { get; set; }
public double USDGMD { get; set; }
public double USDGNF { get; set; }
public double USDGTQ { get; set; }
public double USDGYD { get; set; }
public double USDHKD { get; set; }
public double USDHNL { get; set; }
public double USDHRK { get; set; }
public double USDHTG { get; set; }
public double USDHUF { get; set; }
public int USDIDR { get; set; }
public double USDILS { get; set; }
public double USDIMP { get; set; }
public double USDINR { get; set; }
public int USDIQD { get; set; }
public double USDIRR { get; set; }
public double USDISK { get; set; }
public double USDJEP { get; set; }
public double USDJMD { get; set; }
public double USDJOD { get; set; }
public double USDJPY { get; set; }
public double USDKES { get; set; }
public double USDKGS { get; set; }
public double USDKHR { get; set; }
public double USDKMF { get; set; }
public double USDKPW { get; set; }
public double USDKRW { get; set; }
public double USDKWD { get; set; }
public double USDKYD { get; set; }
public double USDKZT { get; set; }
public double USDLAK { get; set; }
public double USDLBP { get; set; }
public double USDLKR { get; set; }
public double USDLRD { get; set; }
public double USDLSL { get; set; }
public double USDLTL { get; set; }
public double USDLVL { get; set; }
public double USDLYD { get; set; }
public double USDMAD { get; set; }
public double USDMDL { get; set; }
public double USDMGA { get; set; }
public double USDMKD { get; set; }
public double USDMMK { get; set; }
public double USDMNT { get; set; }
public double USDMOP { get; set; }
public double USDMRO { get; set; }
public double USDMUR { get; set; }
public double USDMVR { get; set; }
public double USDMWK { get; set; }
public double USDMXN { get; set; }
public double USDMYR { get; set; }
public double USDMZN { get; set; }
public double USDNAD { get; set; }
public double USDNGN { get; set; }
public double USDNIO { get; set; }
public double USDNOK { get; set; }
public double USDNPR { get; set; }
public double USDNZD { get; set; }
public double USDOMR { get; set; }
public int USDPAB { get; set; }
public double USDPEN { get; set; }
public double USDPGK { get; set; }
public double USDPHP { get; set; }
public double USDPKR { get; set; }
public double USDPLN { get; set; }
public double USDPYG { get; set; }
public double USDQAR { get; set; }
public double USDRON { get; set; }
public double USDRSD { get; set; }
public double USDRUB { get; set; }
public double USDRWF { get; set; }
public double USDSAR { get; set; }
public double USDSBD { get; set; }
public double USDSCR { get; set; }
public double USDSDG { get; set; }
public double USDSEK { get; set; }
public double USDSGD { get; set; }
public double USDSHP { get; set; }
public double USDSLL { get; set; }
public double USDSOS { get; set; }
public double USDSRD { get; set; }
public double USDSTD { get; set; }
public double USDSVC { get; set; }
public double USDSYP { get; set; }
public double USDSZL { get; set; }
public double USDTHB { get; set; }
public double USDTJS { get; set; }
public double USDTMT { get; set; }
public double USDTND { get; set; }
public double USDTOP { get; set; }
public double USDTRY { get; set; }
public double USDTTD { get; set; }
public double USDTWD { get; set; }
public double USDTZS { get; set; }
public double USDUAH { get; set; }
public double USDUGX { get; set; }
public int USDUSD { get; set; }
public double USDUYU { get; set; }
public double USDUZS { get; set; }
public double USDVEF { get; set; }
public int USDVND { get; set; }
public double USDVUV { get; set; }
public double USDWST { get; set; }
public double USDXAF { get; set; }
public double USDXAG { get; set; }
public double USDXAU { get; set; }
public double USDXCD { get; set; }
public double USDXDR { get; set; }
public double USDXOF { get; set; }
public double USDXPF { get; set; }
public double USDYER { get; set; }
public double USDZAR { get; set; }
public double USDZMK { get; set; }
public double USDZMW { get; set; }
public double USDZWL { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public string terms { get; set; }
public string privacy { get; set; }
public int timestamp { get; set; }
public string source { get; set; }
public Quotes quotes { get; set; }
}
use JsonConvert.DeserializeObject<T> method to get model.
var jsonObj = JsonConvert.DeserializeObject<RootObject>(jsonData);
var USDEUR = jsonObj.quotes.USDEUR //object property to get your field.
use JObject.Parse method to Parse json
sample code:
string url = #"http://apilayer.net/api/live? access_key=8efc5a54419e913b695f694bbef4d97f& currencies = EUR,GBP,CAD,PLN& source = USD& format = 1";
string objects = new WebClient().DownloadString(url);
var jsonObj= JObject.Parse(objects);
string USDEUR = (string)jsonObj["quotes"]["USDEUR"];
C# ONLINE
Note:
There are two way can create model easily.
You can use Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class, you can easier to know the relation between Json and model.
If you can't use Web Essentials you can instead http://json2csharp.com/ online JSON to Model class.

How to grab second occurring name from xml api data with C#

I'm trying to grab the high and low from this api, I am able to get the High, but can't figure out what to do to get the Low, which is the second occurring item with the name "fahrenheit", how could I do this using the same method I used for getting the High?
if (xmlForecast.Name == "fahrenheit" && i == 0)
{
i++;
xmlHigh = xmlForecast.ReadString();
}
Since you want solution using XML response, here it is:
First, you'll need to create classes which will represent XML response.
[XmlRoot("response")]
public class Response
{
[XmlElement("version")]
public string Version { get; set; }
[XmlElement("termsofService")]
public string TermsOfService { get; set; }
[XmlElement("features")]
public Features Features { get; set; }
[XmlElement("forecast")]
public Forecast Forecast { get; set; }
}
public class Features
{
[XmlElement("forecast")]
public int Forecast { get; set; }
}
public class Forecast
{
[XmlElement("txt_forecast")]
public TxtForecast TxtForecast { get; set; }
[XmlElement("simpleforecast")]
public SimpleForecast SimpleForecast { get; set; }
}
public class TxtForecast
{
[XmlElement("date")]
public string Date { get; set; }
[XmlArray("forecastdays")]
[XmlArrayItem("forecastday")]
public List<ForecastDay> ForecastDays { get; set; }
}
public class ForecastDay
{
[XmlElement("period")]
public int Period { get; set; }
[XmlElement("icon")]
public string Icon { get; set; }
[XmlElement("icon_url")]
public string IconUrl { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("fcttext")]
public string FctText { get; set; }
[XmlElement("fcttext_metric")]
public string FctTextMetric { get; set; }
[XmlElement("pop")]
public string Pop { get; set; }
}
public class SimpleForecast
{
[XmlArray("forecastdays")]
[XmlArrayItem("forecastday")]
public List<ForecastDay2> ForecastDays { get; set; }
}
public class ForecastDay2
{
[XmlElement("date")]
public Date Date { get; set; }
[XmlElement("period")]
public int Period { get; set; }
[XmlElement("high")]
public High High { get; set; }
[XmlElement("low")]
public Low Low { get; set; }
[XmlElement("conditions")]
public string Conditions { get; set; }
[XmlElement("icon")]
public string Icon { get; set; }
[XmlElement("icon_url")]
public string IconUrl { get; set; }
[XmlElement("skyicon")]
public string SkyIcon { get; set; }
[XmlElement("pop")]
public int Pop { get; set; }
[XmlElement("qpf_allday")]
public QpfAllday QpfAllDay { get; set; }
[XmlElement("qpf_day")]
public QpfDay QpfDay { get; set; }
[XmlElement("qpf_night")]
public QpfNight QpfNight { get; set; }
[XmlElement("snow_allday")]
public SnowAllday SnowAllday { get; set; }
[XmlElement("snow_day")]
public SnowDay SnowDay { get; set; }
[XmlElement("snow_night")]
public SnowNight SnowNight { get; set; }
[XmlElement("maxwind")]
public MaxWind MaxWind { get; set; }
[XmlElement("avewind")]
public AveWind AveWind { get; set; }
[XmlElement("avehumidity")]
public int AveHumidity { get; set; }
[XmlElement("maxhumidity")]
public int MaxHumidity { get; set; }
[XmlElement("minhumidity")]
public int MinHumidity { get; set; }
}
public class Date
{
[XmlElement("epoch")]
public string Epoch { get; set; }
[XmlElement("pretty")]
public string Pretty { get; set; }
[XmlElement("day")]
public int Day { get; set; }
[XmlElement("month")]
public int Month { get; set; }
[XmlElement("year")]
public int Year { get; set; }
[XmlElement("yday")]
public int Yesterday { get; set; }
[XmlElement("hour")]
public int Hour { get; set; }
[XmlElement("min")]
public string Min { get; set; }
[XmlElement("sec")]
public int Sec { get; set; }
[XmlElement("isdst")]
public string Isdst { get; set; }
[XmlElement("monthname")]
public string MonthName { get; set; }
[XmlElement("monthname_short")]
public string MonthNameShort { get; set; }
[XmlElement("weekday_short")]
public string WeekdayShort { get; set; }
[XmlElement("weekday")]
public string Weekday { get; set; }
[XmlElement("ampm")]
public string AmPM { get; set; }
[XmlElement("tz_short")]
public string TzShort { get; set; }
[XmlElement("tz_long")]
public string TzLong { get; set; }
}
public class High
{
[XmlElement("fahrenheit")]
public string Fahrenheit { get; set; }
[XmlElement("celsius")]
public string Celsius { get; set; }
}
public class Low
{
[XmlElement("fahrenheit")]
public string Fahrenheit { get; set; }
[XmlElement("celsius")]
public string Celsius { get; set; }
}
public class QpfAllday
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("mm")]
public int Milimeters { get; set; }
}
public class QpfDay
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("mm")]
public int Milimeters { get; set; }
}
public class QpfNight
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("mm")]
public int Milimeters { get; set; }
}
public class SnowAllday
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("cm")]
public double Centimeters { get; set; }
}
public class SnowDay
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("cm")]
public double Centimeters { get; set; }
}
public class SnowNight
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("cm")]
public double Centimeters { get; set; }
}
public class MaxWind
{
[XmlElement("mph")]
public int Mph { get; set; }
[XmlElement("kph")]
public int Kph { get; set; }
[XmlElement("dir")]
public string Direction { get; set; }
[XmlElement("degrees")]
public int Degrees { get; set; }
}
public class AveWind
{
[XmlElement("mph")]
public int Mph { get; set; }
[XmlElement("kph")]
public int Kph { get; set; }
[XmlElement("dir")]
public string Direction { get; set; }
[XmlElement("degrees")]
public int Degrees { get; set; }
}
Secondly, you need to deserialize XML into Response
using (HttpClient client = new HttpClient())
{
using (var stream = await client.GetStreamAsync("http://api.wunderground.com/api/ea4bb7e7839782da/forecast/q/CA/San_Francisco.xml"))
{
var serializer = new XmlSerializer(typeof(Response));
var response = (Response)serializer.Deserialize(stream);
var simpleForecast = response.Forecast.SimpleForecast;
var forecastDays = simpleForecast.ForecastDays;
var latestForecastDay = forecastDays.Last();
var latestHighFahrenheit = latestForecastDay.High.Fahrenheit;
var latestLowFahrenheit = latestForecastDay.Low.Fahrenheit;
}
}
I am using XmlSerializer but you can also use DataContractSerializer which is newer. If you decide to use DataContractSerializer keep in mind that you'll need to replace XmlElement attributes with DataContract and DataMember.
Note: I've intentionally added few unnecessary steps and variable declarations, so you can see clearly what's going on here.

json feed as a datasource in SSIS

I am trying to deserialize a json feed from openweathermap.org api. After a lot of tries all, using script transformation task, I get is errors and even different ones. Based on the below classes generated by JSON, how I should write the for each statements (as class Weather and Main are part of class RootObject)?
I can get even XML data from api, instead of JSON. Would it be easier to implement the process?
I am not asking for the answer, just a push to start.
JSON:
{
"coord":{
"lon":-122.08,
"lat":37.39
},
"weather":[
{
"id":741,
"main":"Fog",
"description":"fog",
"icon":"50n"
}
],
"base":"stations",
"main":{
"temp":286.14,
"pressure":1022,
"humidity":82,
"temp_min":285.15,
"temp_max":287.15
},
"visibility":16093,
"wind":{
"speed":1.11,
"deg":13.5055
},
"clouds":{
"all":1
},
"dt":1479110160,
"sys":{
"type":1,
"id":397,
"message":0.1452,
"country":"US",
"sunrise":1479134859,
"sunset":1479171466
},
"id":5375480,
"name":"Mountain View",
"cod":200
}
Class:
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int pressure { get; set; }
public int humidity { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class Sys
{
public int type { get; set; }
public int id { get; set; }
public double message { get; set; }
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string #base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}

Categories

Resources