Extracting hair color from JSON array - c#

I am stuck with a small problem of extracting the first color of the persons hair from JSON data. I am very new to this and am having little success with it. Please help
Any ideas as to how I can get the color of the hair out and setting it to a string?
[{"faceId":"b5472f5d-f6f2-41bd-9c52-cb585372108c","faceRectangle":{"top":1005,"left":786,"width":864,"height":864},"faceAttributes":{"smile":0.185,"headPose":{"pitch":0.0,"roll":-7.6,"yaw":9.2},"gender":"male","age":41.8,"facialHair":{"moustache":0.8,"beard":1.0,"sideburns":0.9},"glasses":"NoGlasses","emotion":{"anger":0.004,"contempt":0.012,"disgust":0.006,"fear":0.057,"happiness":0.185,"neutral":0.516,"sadness":0.043,"surprise":0.177},"blur":{"blurLevel":"medium","value":0.32},"exposure":{"exposureLevel":"goodExposure","value":0.6},"noise":{"noiseLevel":"high","value":1.0},"makeup":{"eyeMakeup":false,"lipMakeup":false},"accessories":[],"occlusion":{"foreheadOccluded":false,"eyeOccluded":false,"mouthOccluded":false},"hair":{"bald":0.05,"invisible":false,"hairColor":[{"color":"black","confidence":0.97},{"color":"brown","confidence":0.89},{"color":"other","confidence":0.41},{"color":"gray","confidence":0.22},{"color":"blond","confidence":0.17},{"color":"red","confidence":0.09}]}}}]
This is how I am trying to access the color but to no avail
string x = myObj.faceAttributes.hair.hairColor.ToString();
This is what I get back:
Debug Result: System.Collections.Generic.List`1[Namespace.Model.HairColor]
Here are the classes:
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class HeadPose
{
public double pitch { get; set; }
public double roll { get; set; }
public double yaw { get; set; }
}
public class FacialHair
{
public double moustache { get; set; }
public double beard { get; set; }
public double sideburns { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class Blur
{
public string blurLevel { get; set; }
public double value { get; set; }
}
public class Exposure
{
public string exposureLevel { get; set; }
public double value { get; set; }
}
public class Noise
{
public string noiseLevel { get; set; }
public double value { get; set; }
}
public class Makeup
{
public bool eyeMakeup { get; set; }
public bool lipMakeup { get; set; }
}
public class Occlusion
{
public bool foreheadOccluded { get; set; }
public bool eyeOccluded { get; set; }
public bool mouthOccluded { get; set; }
}
public class HairColor
{
public string color { get; set; }
public double confidence { get; set; }
}
public class Hair
{
public double bald { get; set; }
public bool invisible { get; set; }
public List<HairColor> hairColor { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public HeadPose headPose { get; set; }
public string gender { get; set; }
public double age { get; set; }
public FacialHair facialHair { get; set; }
public string glasses { get; set; }
public Emotion emotion { get; set; }
public Blur blur { get; set; }
public Exposure exposure { get; set; }
public Noise noise { get; set; }
public Makeup makeup { get; set; }
public List<object> accessories { get; set; }
public Occlusion occlusion { get; set; }
public Hair hair { get; set; }
}
public class Face
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}
}
Please help!

hairColor is an array, so you have to specify which element you want.
string x = myObj.faceAttributes.hair.hairColor[0].color;

If you have a look at the class structure, you will see that Hair contains a List of Hair Colour. The debug message is also telling you the same thing; that you are calling ToString() on a List.
Instead the correct approach would be to print out each of the Hair colours, either separately or as a comma separated value. Without knowing exactly how you want to output/use the hair colour(s) try one of the approaches below.
Comma Separated: This will produce a string of comma separated hair colours
string x = string.Join(",", myObj.faceAttributes.hair.hairColor);
For Each:
foreach (string x in myObj.faceAttributes.hair.hairColor)
{
System.Out.WriteLine(x);
// Or whatever else you would like to do with this.
}

Related

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

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
}

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:

Deserializing JSON data to C#

Could U help me Deserializing JSON to C#? I just eat my teeth on it.. =.=.
I find many methods how to do not solve this xD,
I dont want share that with U.
I wish to wait for your suggestions.
Usefull links:
http://jsonviewer.stack.hu/
http://json2csharp.com/
JSON looks..
[
{
"faceId":"626f5974-1d63-40d4-98f1-7e6a7df13dba",
"faceRectangle":{
"top":108,
"left":699,
"width":208,
"height":208
},
"faceAttributes":{
"smile":0.973,
"gender":"male",
"age":25.7,
"emotion":{
"anger":0.0,
"contempt":0.026,
"disgust":0.0,
"fear":0.0,
"happiness":0.973,
"neutral":0.001,
"sadness":0.0,
"surprise":0.0
}
}
},
{
"faceId":"bc051f1d-9a64-4e86-bf95-2af1de21d316",
"faceRectangle":{
"top":104,
"left":634,
"width":114,
"height":114
},
"faceAttributes":{
"smile":0.074,
"gender":"male",
"age":17.4,
"emotion":{
"anger":0.003,
"contempt":0.003,
"disgust":0.001,
"fear":0.002,
"happiness":0.074,
"neutral":0.828,
"sadness":0.079,
"surprise":0.01
}
}
}
]
First of all you need classes to which you want to deserialize, so you can create manually or the fastest and easiest way - you can copy json string that you have, then in visual studio
Edit -> Paste Special -> Paste JSON as Classes
Now you have structure for deserializing.Then you can for example use Newtonsoft.Json (which you can download from NuGet). There is JsonConvert.DeserializeObject<T>() generic method, that will do all deserialization work for you.
Also, if you want use your own property names in the class structure, you can use [JsonProperty("Name")] attribute, which will change the names of properties when they are serialized to JSON and vice versa.
Your JSON document represents an array so you must deserialize it to a collection
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string jsonString = "[ {\"faceId\": \"626f5974-1d63-40d4-98f1-7e6a7df13dba\",\"faceRectangle\": { \"top\": 108, \"left\": 699, \"width\": 208, \"height\": 208 },\"faceAttributes\": { \"smile\": 0.973, \"gender\": \"male\", \"age\": 25.7, \"emotion\": { \"anger\": 0.0, \"contempt\": 0.026, \"disgust\": 0.0, \"fear\": 0.0, \"happiness\": 0.973, \"neutral\": 0.001, \"sadness\": 0.0, \"surprise\": 0.0 } }},{\"faceId\": \"bc051f1d-9a64-4e86-bf95-2af1de21d316\",\"faceRectangle\": { \"top\": 104, \"left\": 634, \"width\": 114, \"height\": 114 },\"faceAttributes\": { \"smile\": 0.074, \"gender\": \"male\", \"age\": 17.4, \"emotion\": { \"anger\": 0.003, \"contempt\": 0.003, \"disgust\": 0.001, \"fear\": 0.002, \"happiness\": 0.074, \"neutral\": 0.828, \"sadness\": 0.079, \"surprise\": 0.01 } }}]";
var result = JsonConvert.DeserializeObject<IList<RootObject>>(jsonString);
foreach ( var item in result )
Console.WriteLine( item.faceId );
}
}
// Generated by http://json2csharp.com
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public string gender { get; set; }
public double age { get; set; }
public Emotion emotion { get; set; }
}
public class RootObject
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}
.net fiddle
If you want c# object from that JSON, this is how it is done:
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public string gender { get; set; }
public double age { get; set; }
public Emotion emotion { get; set; }
}
public class RootObject
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Instead of giving you a C# class that maps to the JSON which you'll just copy blindly, I'll recommend that you generate such a class yourself.
Make sure you're running Visual Studio 2013 SP2 or higher.
Get a JSON document for your data. If it has optional fields, make sure the one you have is as full as possible.
In a new CS file in VS, choose Edit -> Paste Special -> Paste JSON as Classes.
This will create a C# class that corresponds to the JSON data. Now, you can use JSON.NET's JsonConvert.DeserializeObject() to create it
By using NewtonsoftJson library to parse data easily
Example
dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject(Jsondata); //to parse data
foreach (var product in x) {
Messagebox.show(product.data.ToString());
}
You can convert Json to c# Class
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public string gender { get; set; }
public double age { get; set; }
public Emotion emotion { get; set; }
}
public class Example
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}
Example Example_class =
Newtonsoft.Json.JsonConvert.DeserializeObject<Example>(json.ToString());
Please see this useful link Json to C# Class https://jsonutils.com/
Do you mean something like this? To deserialize to an object?
using System.Web.Script.Serialization;
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public string gender { get; set; }
public double age { get; set; }
public Emotion emotion { get; set; }
}
public class RootObject
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}
return JsonConvert.DeserializeObject<RootObject>(jsonString);
I hope this will work
string Jsondata = "Your Json data";
public class Mainclass
{
public guid faceId;
IEnumerable<faceRectangle>
IEnumerable<faceAttributes>
}
public class faceRectangle
{
}
public class faceAttributes
{
}
Mainclass backdata = JsonConvert.DeserializeObject<Mainclass>(Jsondata , new DataConverter())

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