How to print all dates from Weather API XML - c#

Sorry for any lq thing, am new to c#.
Am trying to display all dates from XML WEB API...
I already printed for only 1 date, I want for 5 days?
I need to display in Console application all data for 5 days just like I post for one date.
What should I use, can anyone help me please?
replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.replacing text, because stack doesn't let me post, says mostly code.
static void Main(string[] args)
{
var clientWeather = new RestClient("http://api.worldweatheronline.com/premium/v1/weather.ashx");//?key=c37f984779f14beb9bf01943201104&q=Pristina&format=json&num_of_days=5");
//client.Timeout = -1;
var requestWeather = new RestRequest(Method.GET);
requestWeather.AddParameter("key", "c37f984779f14beb9bf01943201104", ParameterType.QueryString);
requestWeather.AddParameter("q", "London", ParameterType.QueryString);
requestWeather.AddParameter("format", "xml", ParameterType.QueryString);
requestWeather.AddParameter("num_of_days", "5", ParameterType.QueryString);
IRestResponse responseWeather = clientWeather.Execute(requestWeather);
var xmlDeserializer = new XmlDeserializer();
var place = xmlDeserializer.Deserialize<Request>(responseWeather);
var temp = xmlDeserializer.Deserialize<Current_condition>(responseWeather);
var dit = xmlDeserializer.Deserialize<Weather>(responseWeather);
var data1 = xmlDeserializer.Deserialize<Data>(responseWeather);
Console.WriteLine("Place: " + place.Query);
Console.WriteLine("Temp momentale: " + temp.FeelsLikeC);
Console.WriteLine("Temp for 5 days.");
Console.Write("Date " + "TempMin " );
Console.WriteLine("TempMax");
Console.WriteLine(dit.Date + " " + dit.MintempC + " " + dit.MaxtempC);
Console.ReadLine();
Console.ReadLine();
}
[XmlRoot(ElementName = "request")]
public class Request
{
[XmlElement(ElementName = "type")]
public string Type { get; set; }
[XmlElement(ElementName = "query")]
public string Query { get; set; }
}
[XmlRoot(ElementName = "current_condition")]
public class Current_condition
{
[XmlElement(ElementName = "observation_time")]
public string Observation_time { get; set; }
[XmlElement(ElementName = "temp_C")]
public string Temp_C { get; set; }
[XmlElement(ElementName = "temp_F")]
public string Temp_F { get; set; }
[XmlElement(ElementName = "weatherCode")]
public string WeatherCode { get; set; }
[XmlElement(ElementName = "weatherIconUrl")]
public string WeatherIconUrl { get; set; }
[XmlElement(ElementName = "weatherDesc")]
public string WeatherDesc { get; set; }
[XmlElement(ElementName = "windspeedMiles")]
public string WindspeedMiles { get; set; }
[XmlElement(ElementName = "windspeedKmph")]
public string WindspeedKmph { get; set; }
[XmlElement(ElementName = "winddirDegree")]
public string WinddirDegree { get; set; }
[XmlElement(ElementName = "winddir16Point")]
public string Winddir16Point { get; set; }
[XmlElement(ElementName = "precipMM")]
public string PrecipMM { get; set; }
[XmlElement(ElementName = "precipInches")]
public string PrecipInches { get; set; }
[XmlElement(ElementName = "humidity")]
public string Humidity { get; set; }
[XmlElement(ElementName = "visibility")]
public string Visibility { get; set; }
[XmlElement(ElementName = "visibilityMiles")]
public string VisibilityMiles { get; set; }
[XmlElement(ElementName = "pressure")]
public string Pressure { get; set; }
[XmlElement(ElementName = "pressureInches")]
public string PressureInches { get; set; }
[XmlElement(ElementName = "cloudcover")]
public string Cloudcover { get; set; }
[XmlElement(ElementName = "FeelsLikeC")]
public string FeelsLikeC { get; set; }
[XmlElement(ElementName = "FeelsLikeF")]
public string FeelsLikeF { get; set; }
[XmlElement(ElementName = "uvIndex")]
public string UvIndex { get; set; }
}
[XmlRoot(ElementName = "astronomy")]
public class Astronomy
{
[XmlElement(ElementName = "sunrise")]
public string Sunrise { get; set; }
[XmlElement(ElementName = "sunset")]
public string Sunset { get; set; }
[XmlElement(ElementName = "moonrise")]
public string Moonrise { get; set; }
[XmlElement(ElementName = "moonset")]
public string Moonset { get; set; }
[XmlElement(ElementName = "moon_phase")]
public string Moon_phase { get; set; }
[XmlElement(ElementName = "moon_illumination")]
public string Moon_illumination { get; set; }
}
[XmlRoot(ElementName = "hourly")]
public class Hourly
{
[XmlElement(ElementName = "time")]
public string Time { get; set; }
[XmlElement(ElementName = "tempC")]
public string TempC { get; set; }
[XmlElement(ElementName = "tempF")]
public string TempF { get; set; }
[XmlElement(ElementName = "windspeedMiles")]
public string WindspeedMiles { get; set; }
[XmlElement(ElementName = "windspeedKmph")]
public string WindspeedKmph { get; set; }
[XmlElement(ElementName = "winddirDegree")]
public string WinddirDegree { get; set; }
[XmlElement(ElementName = "winddir16Point")]
public string Winddir16Point { get; set; }
[XmlElement(ElementName = "weatherCode")]
public string WeatherCode { get; set; }
[XmlElement(ElementName = "weatherIconUrl")]
public string WeatherIconUrl { get; set; }
[XmlElement(ElementName = "weatherDesc")]
public string WeatherDesc { get; set; }
[XmlElement(ElementName = "precipMM")]
public string PrecipMM { get; set; }
[XmlElement(ElementName = "precipInches")]
public string PrecipInches { get; set; }
[XmlElement(ElementName = "humidity")]
public string Humidity { get; set; }
[XmlElement(ElementName = "visibility")]
public string Visibility { get; set; }
[XmlElement(ElementName = "visibilityMiles")]
public string VisibilityMiles { get; set; }
[XmlElement(ElementName = "pressure")]
public string Pressure { get; set; }
[XmlElement(ElementName = "pressureInches")]
public string PressureInches { get; set; }
[XmlElement(ElementName = "cloudcover")]
public string Cloudcover { get; set; }
[XmlElement(ElementName = "HeatIndexC")]
public string HeatIndexC { get; set; }
[XmlElement(ElementName = "HeatIndexF")]
public string HeatIndexF { get; set; }
[XmlElement(ElementName = "DewPointC")]
public string DewPointC { get; set; }
[XmlElement(ElementName = "DewPointF")]
public string DewPointF { get; set; }
[XmlElement(ElementName = "WindChillC")]
public string WindChillC { get; set; }
[XmlElement(ElementName = "WindChillF")]
public string WindChillF { get; set; }
[XmlElement(ElementName = "WindGustMiles")]
public string WindGustMiles { get; set; }
[XmlElement(ElementName = "WindGustKmph")]
public string WindGustKmph { get; set; }
[XmlElement(ElementName = "FeelsLikeC")]
public string FeelsLikeC { get; set; }
[XmlElement(ElementName = "FeelsLikeF")]
public string FeelsLikeF { get; set; }
[XmlElement(ElementName = "chanceofrain")]
public string Chanceofrain { get; set; }
[XmlElement(ElementName = "chanceofremdry")]
public string Chanceofremdry { get; set; }
[XmlElement(ElementName = "chanceofwindy")]
public string Chanceofwindy { get; set; }
[XmlElement(ElementName = "chanceofovercast")]
public string Chanceofovercast { get; set; }
[XmlElement(ElementName = "chanceofsunshine")]
public string Chanceofsunshine { get; set; }
[XmlElement(ElementName = "chanceoffrost")]
public string Chanceoffrost { get; set; }
[XmlElement(ElementName = "chanceofhightemp")]
public string Chanceofhightemp { get; set; }
[XmlElement(ElementName = "chanceoffog")]
public string Chanceoffog { get; set; }
[XmlElement(ElementName = "chanceofsnow")]
public string Chanceofsnow { get; set; }
[XmlElement(ElementName = "chanceofthunder")]
public string Chanceofthunder { get; set; }
[XmlElement(ElementName = "uvIndex")]
public string UvIndex { get; set; }
}
[XmlRoot(ElementName = "weather")]
public class Weather
{
[XmlElement(ElementName = "date")]
public string Date { get; set; }
[XmlElement(ElementName = "astronomy")]
public Astronomy Astronomy { get; set; }
[XmlElement(ElementName = "maxtempC")]
public string MaxtempC { get; set; }
[XmlElement(ElementName = "maxtempF")]
public string MaxtempF { get; set; }
[XmlElement(ElementName = "mintempC")]
public string MintempC { get; set; }
[XmlElement(ElementName = "mintempF")]
public string MintempF { get; set; }
[XmlElement(ElementName = "avgtempC")]
public string AvgtempC { get; set; }
[XmlElement(ElementName = "avgtempF")]
public string AvgtempF { get; set; }
[XmlElement(ElementName = "totalSnow_cm")]
public string TotalSnow_cm { get; set; }
[XmlElement(ElementName = "sunHour")]
public string SunHour { get; set; }
[XmlElement(ElementName = "uvIndex")]
public string UvIndex { get; set; }
[XmlElement(ElementName = "hourly")]
public List<Hourly> Hourly { get; set; }
}
[XmlRoot(ElementName = "month")]
public class Month
{
[XmlElement(ElementName = "index")]
public string Index { get; set; }
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "avgMinTemp")]
public string AvgMinTemp { get; set; }
[XmlElement(ElementName = "avgMinTemp_F")]
public string AvgMinTemp_F { get; set; }
[XmlElement(ElementName = "absMaxTemp")]
public string AbsMaxTemp { get; set; }
[XmlElement(ElementName = "absMaxTemp_F")]
public string AbsMaxTemp_F { get; set; }
[XmlElement(ElementName = "avgDailyRainfall")]
public string AvgDailyRainfall { get; set; }
}
[XmlRoot(ElementName = "ClimateAverages")]
public class ClimateAverages
{
[XmlElement(ElementName = "month")]
public List<Month> Month { get; set; }
}
[XmlRoot(ElementName = "data")]
public class Data
{
[XmlElement(ElementName = "request")]
public Request Request { get; set; }
[XmlElement(ElementName = "current_condition")]
public Current_condition Current_condition { get; set; }
[XmlElement(ElementName = "weather")]
public List<Weather> Weather { get; set; }
[XmlElement(ElementName = "ClimateAverages")]
public ClimateAverages ClimateAverages { get; set; }
}
}
}

You can deserialize xml to a collection of specific objects, like this:
//request and response code omitted for brevity
var dit = xmlDeserializer.Deserialize<List<Weather>>(responseWeather);
foreach(var date in dit)
{
Console.WriteLine(date.Date + " " + date.MintempC + " " + date.MaxtempC);
}
output:
2020-04-20 9 15
2020-04-21 9 15
2020-04-22 11 16
2020-04-23 12 20
2020-04-24 11 19

I modified the URL. You were getting json and not xml. See xml linq below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
const string URL = "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=c37f984779f14beb9bf01943201104&q=Pristina&num_of_days=5";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(URL);
List<TemperatureDate> dates = doc.Descendants("weather").Select(x => new TemperatureDate()
{
date = (DateTime)x.Element("date"),
avgtempF = (int)x.Element("avgtempF"),
hourTemp = x.Elements("hourly").Select(y => new KeyValuePair<int,int>(((int)y.Element("time"))/100, (int)y.Element("tempF"))).ToList()
}).ToList();
}
}
public class TemperatureDate
{
public DateTime date { get; set; }
public int avgtempF { get; set; }
public List<KeyValuePair<int, int>> hourTemp { get; set; }
}
}
using serialization
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string URL = "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=c37f984779f14beb9bf01943201104&q=Pristina&num_of_days=5";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(URL);
XmlSerializer serializer = new XmlSerializer(typeof(data));
data data = (data)serializer.Deserialize(reader);
}
}
public class data
{
public request request { get; set; }
public current_condition current_condition { get; set; }
public weather weather { get; set; }
}
public class request
{
[XmlElement("type")]
public string _type { get; set; }
public string query { get; set; }
}
public class current_condition
{
public TimeSpan observation_time { get; set; }
public int temp_C { get; set; }
public int temp_F { get; set; }
public int weatherCode { get; set; }
public string weatherIconUrl { get; set; }
public string weatherDesc { get; set; }
public int windspeedMiles { get; set; }
public int windspeedKmph { get; set; }
public int winddirDegree { get; set; }
public string winddir16Point { get; set; }
public decimal precipMM { get; set; }
public decimal precipInches { get; set; }
public int humidity { get; set; }
public int visibility { get; set; }
public int visibilityMiles { get; set; }
public int pressure { get; set; }
public int pressureInches { get; set; }
public int cloudcover { get; set; }
public int FeelsLikeC { get; set; }
public int FeelsLikeF { get; set; }
public int uvIndex { get; set; }
}
public class weather
{
public DateTime date { get; set; }
public astronomy astronomy { get; set; }
public int maxtempC { get; set; }
public int maxtempF { get; set; }
public int mintempC { get; set; }
public int mintempF { get; set; }
public int avgtempC { get; set; }
public int avgtempF { get; set; }
public decimal totalSnow_cm { get; set; }
public decimal sunHour { get; set; }
public int uvIndex { get; set; }
[XmlElement("hourly")]
public List<hourly> hourly { get; set; }
}
public class astronomy
{
public TimeSpan sunrise { get; set; }
public TimeSpan sunset { get; set; }
public TimeSpan moonrise { get; set; }
public TimeSpan moonset { get; set; }
public string moon_phase { get; set; }
public int moon_illumination { get; set; }
}
public class hourly
{
public int time { get; set; }
public int tempC { get; set; }
public int tempF { get; set; }
public int windspeedMiles { get; set; }
public int windspeedKmph { get; set; }
public int winddirDegree { get; set; }
public string winddir16Point { get; set; }
public int weatherCode { get; set; }
public string weatherIconUrl { get; set; }
public string weatherDesc { get; set; }
public decimal precipMM { get; set; }
public decimal precipInches { get; set; }
public int humidity { get; set; }
public int visibility { get; set; }
public int visibilityMiles { get; set; }
public int pressure { get; set; }
public int pressureInches { get; set; }
public int cloudcover { get; set; }
public int HeatIndexC { get; set; }
public int HeatIndexF { get; set; }
public int DewPointC { get; set; }
public int DewPointF { get; set; }
public int WindChillC { get; set; }
public int WindChillF { get; set; }
public int WindGustMiles { get; set; }
public int WindGustKmph { get; set; }
public int FeelsLikeC { get; set; }
public int FeelsLikeF { get; set; }
public int chanceofrain { get; set; }
public int chanceofremdry { get; set; }
public int chanceofwindy { get; set; }
public int chanceofovercast { get; set; }
public int chanceofsunshine { get; set; }
public int chanceoffrost { get; set; }
public int chanceofhightemp { get; set; }
public int chanceoffog { get; set; }
public int chanceofsnow { get; set; }
public int chanceofthunder { get; set; }
public int uvIndex { get; set; }
}
}

Related

Given json as a response but not sure how to parse it

I am using this code to attempt to parse my response back from the payment gateway:
var responseMessage = client.PostAsJsonAsync("transaction", transData).Result;
var response = responseMessage.Content.ReadAsStringAsync().Result;
MessageBox.Show(response);
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
var objCustomer = jsonSerializer.Deserialize<ReturnValues.RootObject>(response);
This is the class I am trying to create:
public class ReturnValues
{
public class Card
{
public string id { get; set; }
public string card_type { get; set; }
public string first_six { get; set; }
public string last_four { get; set; }
public string masked_card { get; set; }
public string expiration_date { get; set; }
public string status { get; set; }
public string auth_code { get; set; }
public string processor_response_code { get; set; }
public string processor_response_text { get; set; }
public string processor_type { get; set; }
public string processor_id { get; set; }
public string avs_response_code { get; set; }
public string cvv_response_code { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class Response
{
public Card card { get; set; }
}
public class BillingAddress
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
public class ShippingAddress
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
public class Data
{
public string id { get; set; }
public string type { get; set; }
public int amount { get; set; }
public int tax_amount { get; set; }
public bool tax_exempt { get; set; }
public int shipping_amount { get; set; }
public int discount_amount { get; set; }
public string payment_adjustment_type { get; set; }
public int payment_adjustment_value { get; set; }
public string currency { get; set; }
public string description { get; set; }
public string order_id { get; set; }
public string po_number { get; set; }
public string ip_address { get; set; }
public bool email_receipt { get; set; }
public string email_address { get; set; }
public string payment_method { get; set; }
public Response response { get; set; }
public string status { get; set; }
public int response_code { get; set; }
public string customer_id { get; set; }
public BillingAddress billing_address { get; set; }
public ShippingAddress shipping_address { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class RootObject
{
public string status { get; set; }
public string msg { get; set; }
public Data data { get; set; }
}
}
This is the response I am given:
"{\"status\":\"success\",\"msg\":\"success\",\"data\":{\"id\":\"bp2pa41erttupu3q1eng\",\"user_id\":\"bmibms9erttqdc2kigl0\",\"user_name\":\"dev\",\"merchant_id\":\"asdfasdf\",\"idempotency_key\":\"\",\"idempotency_time\":0,\"type\":\"sale\",\"amount\":1000,\"base_amount\":1000,\"amount_authorized\":1000,\"amount_captured\":1000,\"amount_settled\":0,\"amount_refunded\":0,\"payment_adjustment\":0,\"tip_amount\":0,\"settlement_batch_id\":\"\",\"processor_id\":\"bmibnfperttqdc2kigmg\",\"processor_type\":\"tsys_sierra\",\"processor_name\":\"Keyed
Credit
Cards\",\"payment_method\":\"card\",\"payment_type\":\"card\",\"features\":[\"avs\",\"card_verification\",\"levelii\",\"fake_response\"],\"national_tax_amount\":0,\"duty_amount\":0,\"ship_from_postal_code\":\"\",\"summary_commodity_code\":\"\",\"merchant_vat_registration_number\":\"\",\"customer_vat_registration_number\":\"\",\"tax_amount\":0,\"tax_exempt\":false,\"shipping_amount\":0,\"surcharge\":0,\"discount_amount\":0,\"currency\":\"usd\",\"description\":\"This
is a
test\",\"order_id\":\"555555\",\"po_number\":\"666666\",\"ip_address\":\"1.1.1.1\",\"transaction_source\":\"api\",\"email_receipt\":false,\"email_address\":\"\",\"customer_id\":\"\",\"customer_payment_type\":\"\",\"customer_payment_ID\":\"\",\"subscription_id\":\"\",\"referenced_transaction_id\":\"\",\"response_body\":{\"card\":{\"id\":\"bp2pa41erttupu3q1eo0\",\"card_type\":\"visa\",\"first_six\":\"401288\",\"last_four\":\"1881\",\"masked_card\":\"401288******1881\",\"expiration_date\":\"12/21\",\"response\":\"approved\",\"response_code\":100,\"auth_code\":\"TAS000\",\"processor_response_code\":\"00\",\"processor_response_text\":\"APPROVAL
TAS000
\",\"processor_transaction_id\":\"000000000000000\",\"processor_type\":\"tsys_sierra\",\"processor_id\":\"bmgwgtgtherhemg\",\"avs_response_code\":\"M\",\"cvv_response_code\":\"M\",\"processor_specific\":null,\"created_at\":\"2020-02-13T18:27:28.149933095Z\",\"updated_at\":\"2020-02-13T18:27:28.196367669Z\"}},\"custom_fields\":{},\"line_items\":null,\"status\":\"pending_settlement\",\"response\":\"approved\",\"response_code\":100,\"billing_address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"company\":\"\",\"address_line_1\":\"123
Some
Street\",\"address_line_2\":\"\",\"city\":\"Bessemer\",\"state\":\"AL\",\"postal_code\":\"35020\",\"country\":\"US\",\"phone\":\"5555555555\",\"fax\":\"\",\"email\":\"test#gmail.com\"},\"shipping_address\":{\"first_name\":\"\",\"last_name\":\"\",\"company\":\"\",\"address_line_1\":\"\",\"address_line_2\":\"\",\"city\":\"\",\"state\":\"\",\"postal_code\":\"\",\"country\":\"\",\"phone\":\"\",\"fax\":\"\",\"email\":\"\"},\"created_at\":\"2020-02-13T18:27:28.104845544Z\",\"updated_at\":\"2020-02-13T18:27:28.200963331Z\",\"captured_at\":\"2020-02-13T18:27:28.200962679Z\",\"settled_at\":null}}\n"
I am getting this message:
System.InvalidOperationException: 'Cannot convert object of type
'System.String' to type 'Test.ReturnValues+Response''
I am not sure what I am doing wrong. I used an online json converter to get my class. It appears to be correct.
Any suggestions?
I used json2csharp.com to generate C# classes and it came up with something different.
public class ReturnValues
{
public class Card
{
public string id { get; set; }
public string card_type { get; set; }
public string first_six { get; set; }
public string last_four { get; set; }
public string masked_card { get; set; }
public string expiration_date { get; set; }
public string response { get; set; }
public int response_code { get; set; }
public string auth_code { get; set; }
public string processor_response_code { get; set; }
public string processor_response_text { get; set; }
public string processor_transaction_id { get; set; }
public string processor_type { get; set; }
public string processor_id { get; set; }
public string avs_response_code { get; set; }
public string cvv_response_code { get; set; }
public object processor_specific { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
}
public class ResponseBody
{
public Card card { get; set; }
}
public class CustomFields
{
}
public class BillingAddress
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
public class ShippingAddress
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
public class Data
{
public string id { get; set; }
public string user_id { get; set; }
public string user_name { get; set; }
public string merchant_id { get; set; }
public string idempotency_key { get; set; }
public int idempotency_time { get; set; }
public string type { get; set; }
public int amount { get; set; }
public int base_amount { get; set; }
public int amount_authorized { get; set; }
public int amount_captured { get; set; }
public int amount_settled { get; set; }
public int amount_refunded { get; set; }
public int payment_adjustment { get; set; }
public int tip_amount { get; set; }
public string settlement_batch_id { get; set; }
public string processor_id { get; set; }
public string processor_type { get; set; }
public string processor_name { get; set; }
public string payment_method { get; set; }
public string payment_type { get; set; }
public List<string> features { get; set; }
public int national_tax_amount { get; set; }
public int duty_amount { get; set; }
public string ship_from_postal_code { get; set; }
public string summary_commodity_code { get; set; }
public string merchant_vat_registration_number { get; set; }
public string customer_vat_registration_number { get; set; }
public int tax_amount { get; set; }
public bool tax_exempt { get; set; }
public int shipping_amount { get; set; }
public int surcharge { get; set; }
public int discount_amount { get; set; }
public string currency { get; set; }
public string description { get; set; }
public string order_id { get; set; }
public string po_number { get; set; }
public string ip_address { get; set; }
public string transaction_source { get; set; }
public bool email_receipt { get; set; }
public string email_address { get; set; }
public string customer_id { get; set; }
public string customer_payment_type { get; set; }
public string customer_payment_ID { get; set; }
public string subscription_id { get; set; }
public string referenced_transaction_id { get; set; }
public ResponseBody response_body { get; set; }
public CustomFields custom_fields { get; set; }
public object line_items { get; set; }
public string status { get; set; }
public string response { get; set; }
public int response_code { get; set; }
public BillingAddress billing_address { get; set; }
public ShippingAddress shipping_address { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string captured_at { get; set; }
public object settled_at { get; set; }
}
public class RootObject
{
public string status { get; set; }
public string msg { get; set; }
public Data data { get; set; }
}
}
It seems to work though. I did a quick compare and there are quite a few differences. Might be worth checking out.
use jsoup it is a free framework it parse the document into json format easily
`list<Element> news;
Document doc = Jsoup.connect("https://en.wikipedia.org/").get();
log(doc.title());
Elements newsHeadlines = doc.select("#mp-itn b a");
for (Element headline : news) {
log("%s\n\t%s",
headline.attr("title"), headline.absUrl("href"));
}`

Deserialize JSON using NewtonSoft

I have created classes needed by help of a website, but can't deserialize.
public class Brand
{
public string name { get; set; }
}
public class Link
{
public string href { get; set; }
}
public class Price
{
public double current { get; set; }
}
public class RootObject
{
public Brand brand { get; set; }
public string href { get; set; }
public List<Link> links { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Price price { get; set; }
public string productId { get; set; }
}
How I am trying in C#
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952"
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<RootObject>(result);
foreach (Brand p in jsonresult)
{
Debug.WriteLine(p);
}
I know I'm doing something wrong, but can anyone help me to correctly get the elements from the classes above only?
There are few mistakes in the code you've provided:
The json which is received from endpoint, is a json array.
So, instead of deserialzing as RootObject you should deserialize as List<RootObject>.
While iterating through jsonresult you should use RootObject instead of Brand
So here is the complete solution:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Diagnostics;
public class Brand
{
public string name { get; set; }
}
public class Link
{
public string href { get; set; }
}
public class Price
{
public double current { get; set; }
}
public class RootObject
{
public Brand brand { get; set; }
public string href { get; set; }
public List<Link> links { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Price price { get; set; }
public string productId { get; set; }
}
public class Program
{
public static void Main()
{
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<List<RootObject>>(result);
foreach (RootObject p in jsonresult)
{
Debug.WriteLine(p.brand.name);
foreach (Link link in p.links){
Debug.WriteLine(link.href);
}
foreach (string mpn in p.mpns){
Debug.WriteLine(mpn);
}
}
}
}
And here is the online version just in case it's needed.
Finally, I did it.kindly change your Model. The model should match your JSON data. You can check the complete solution
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
namespace Jsondemo
{
public class Brand
{
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string support { get; set; }
public string url { get; set; }
}
public class Path
{
public string id { get; set; }
public string name { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public List<Path> path { get; set; }
}
public class Installment
{
public int months { get; set; }
public int monthlySum { get; set; }
public double totalAmount { get; set; }
public double annualInterestRate { get; set; }
public double interest { get; set; }
public double fee { get; set; }
}
public class UiLabels
{
public string text { get; set; }
public string price { get; set; }
public string time { get; set; }
public List<string> tooltip { get; set; }
}
public class Installment2
{
public int months { get; set; }
public string monthlySum { get; set; }
public double totalAmount { get; set; }
public double annualInterestRate { get; set; }
public double interest { get; set; }
public double fee { get; set; }
}
public class UiLabels2
{
public string text { get; set; }
public string price { get; set; }
public string time { get; set; }
public List<string> tooltip { get; set; }
}
public class CompanyFinancing
{
public List<Installment2> installments { get; set; }
public UiLabels2 uiLabels { get; set; }
}
public class Financing
{
public List<Installment> installments { get; set; }
public string type { get; set; }
public double price { get; set; }
public UiLabels uiLabels { get; set; }
public CompanyFinancing companyFinancing { get; set; }
}
public class Image
{
public string __invalid_name__45 { get; set; }
public string __invalid_name__90 { get; set; }
public string __invalid_name__300 { get; set; }
public string __invalid_name__500 { get; set; }
public string __invalid_name__960 { get; set; }
public string orig { get; set; }
}
public class Link
{
public string name { get; set; }
public string type { get; set; }
public string href { get; set; }
}
public class Package
{
public int width { get; set; }
public int height { get; set; }
public int depth { get; set; }
public int volume { get; set; }
public int weight { get; set; }
}
public class Price
{
public double current { get; set; }
public double currentTaxless { get; set; }
public string currentFormatted { get; set; }
public double original { get; set; }
public double originalTaxless { get; set; }
public string originalFormatted { get; set; }
public object discountAmount { get; set; }
public object discountPercentage { get; set; }
public int taxRate { get; set; }
public object discount { get; set; }
public object deposit { get; set; }
public object unit { get; set; }
}
public class Rating
{
public int reviewCount { get; set; }
public int averageOverallRating { get; set; }
public int recommendedCount { get; set; }
}
public class Relations
{
public List<object> recommended { get; set; }
public List<object> newer { get; set; }
public List<object> older { get; set; }
public List<object> bundles { get; set; }
}
public class Restrictions
{
public bool isRestricted { get; set; }
public List<object> pickupAllowed { get; set; }
public List<object> postalCodeAllowed { get; set; }
public string description { get; set; }
public string descriptionShort { get; set; }
}
public class ShipmentPrice
{
public int id { get; set; }
public string name { get; set; }
public double price { get; set; }
public bool pickup { get; set; }
}
public class Js
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Pak
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Vendor
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Warehouses
{
public Js js { get; set; }
public Pak pak { get; set; }
public Vendor vendor { get; set; }
}
public class Web
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
public Warehouses warehouses { get; set; }
public string ranking { get; set; }
}
public class Js2
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class JsKioski
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Oul
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pir
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Rai
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu1
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu2
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu3
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu4
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Stores
{
public Js2 js { get; set; }
public JsKioski js_kioski { get; set; }
public Oul oul { get; set; }
public Pir pir { get; set; }
public Rai rai { get; set; }
public Pu1 pu1 { get; set; }
public Pu2 pu2 { get; set; }
public Pu3 pu3 { get; set; }
public Pu4 pu4 { get; set; }
}
public class Stocks
{
public Web web { get; set; }
public Stores stores { get; set; }
}
public class Availability
{
public string _id { get; set; }
public int pid { get; set; }
public object overrideText { get; set; }
public bool isElectronic { get; set; }
public bool isVirtual { get; set; }
public bool isInStoresOnly { get; set; }
public bool isReleased { get; set; }
public bool isShippingAllowed { get; set; }
public bool isPickupAllowed { get; set; }
public bool isStockVisible { get; set; }
public bool isPurchasable { get; set; }
public bool isSoldOut { get; set; }
public bool isEOL { get; set; }
public bool isFastDeliveryAvailable { get; set; }
public bool isStoreOrderAllowed { get; set; }
public bool hasStock { get; set; }
public Stocks stocks { get; set; }
public List<object> tags { get; set; }
public DateTime updatedAt { get; set; }
public DateTime verifiedAt { get; set; }
public int updateCount { get; set; }
public DateTime updateStartTime { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public bool active { get; set; }
public int ageLimit { get; set; }
public Brand brand { get; set; }
public List<string> bulletPoints { get; set; }
public List<object> bundleProducts { get; set; }
public List<object> campaigns { get; set; }
public List<string> categories { get; set; }
public Category category { get; set; }
public DateTime createdAt { get; set; }
public List<object> demoLocations { get; set; }
public string description { get; set; }
public string descriptionShort { get; set; }
public List<string> eans { get; set; }
public bool electronic { get; set; }
public Financing financing { get; set; }
public string freeShipmentFor { get; set; }
public bool hidePriceEstimate { get; set; }
public string href { get; set; }
public List<Image> images { get; set; }
public List<Link> links { get; set; }
public object maxAmountPerOrder { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Package package { get; set; }
public int pid { get; set; }
public Price price { get; set; }
public string productId { get; set; }
public Rating rating { get; set; }
public Relations relations { get; set; }
public DateTime releasedAt { get; set; }
public Restrictions restrictions { get; set; }
public List<string> ribbons { get; set; }
public List<ShipmentPrice> shipmentPrices { get; set; }
public List<object> shopAreas { get; set; }
public bool vak { get; set; }
public int visible { get; set; }
public string warranty { get; set; }
public DateTime updatedAt { get; set; }
public DateTime verifiedAt { get; set; }
public int updateCount { get; set; }
public DateTime updateStartTime { get; set; }
public Availability availability { get; set; }
}
class Program
{
static void Main(string[] args)
{
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<List<RootObject>>(result);
foreach (RootObject p in jsonresult)
{
foreach (var item in p.links)
{
Debug.WriteLine(item.href);
}
}
Console.WriteLine("Hello World!");
}
}
}
You can use https://quicktype.io to generate c# code with entities from JSON.
i have created the c# classes for your json request.
https://app.quicktype.io?share=KNyJfG7rGBZH96H6yNXe

Loading xml causing Deserialize to fail

I have the following xml file which I have tried to load using method to turn it into a business object however it says expecting > at line 1 ,40 but when I look at it looks fine.
XmlSerializer serializer = new XmlSerializer(typeof( SalesOrderXml));
using (TextReader reader = new StringReader(testData))
{
SalesOrderXmlresult = (SalesOrderXml) serializer.Deserialize(reader);
}
Xml here cause of the length of it it would have exceeded the article.
https://pastebin.com/pepp1QDe
I do not no what i am doing wrong as I used the online xml to poco generator to help me out as a its a long file.
Any tips of what i might be doing wrong I checked for hidden chars in the file and there is none.
public class SalesOrderXml
{
[XmlRoot(ElementName = "ORDER_ITEM")]
public class ORDER_ITEM
{
[XmlElement(ElementName = "PRODUCT_ID")]
public string PRODUCT_ID { get; set; }
[XmlElement(ElementName = "STOCK_CODE")]
public string STOCK_CODE { get; set; }
[XmlElement(ElementName = "ITEM_TYPE")]
public string ITEM_TYPE { get; set; }
[XmlElement(ElementName = "DESCRIPTION")]
public string DESCRIPTION { get; set; }
[XmlElement(ElementName = "QUANTITY")]
public string QUANTITY { get; set; }
[XmlElement(ElementName = "PRICE")]
public string PRICE { get; set; }
[XmlElement(ElementName = "HEIGHT")]
public string HEIGHT { get; set; }
[XmlElement(ElementName = "WIDTH")]
public string WIDTH { get; set; }
[XmlElement(ElementName = "HINGE_HOLES")]
public string HINGE_HOLES { get; set; }
[XmlElement(ElementName = "DRILL_TOP")]
public string DRILL_TOP { get; set; }
[XmlElement(ElementName = "DRILL_BOTTOM")]
public string DRILL_BOTTOM { get; set; }
[XmlElement(ElementName = "DRILL_TOP_1")]
public string DRILL_TOP_1 { get; set; }
[XmlElement(ElementName = "DRILL_TOP_2")]
public string DRILL_TOP_2 { get; set; }
[XmlElement(ElementName = "DRILL_TOP_3")]
public string DRILL_TOP_3 { get; set; }
[XmlElement(ElementName = "RAW")]
public string RAW { get; set; }
[XmlElement(ElementName = "RAH")]
public string RAH { get; set; }
[XmlElement(ElementName = "LAW")]
public string LAW { get; set; }
[XmlElement(ElementName = "LAH")]
public string LAH { get; set; }
[XmlElement(ElementName = "FRAME_TYPE")]
public string FRAME_TYPE { get; set; }
[XmlElement(ElementName = "GLAZING_TYPE")]
public string GLAZING_TYPE { get; set; }
[XmlElement(ElementName = "LENGTH")]
public string LENGTH { get; set; }
[XmlElement(ElementName = "DEPTH")]
public string DEPTH { get; set; }
[XmlElement(ElementName = "CORNER_POSITION")]
public string CORNER_POSITION { get; set; }
[XmlElement(ElementName = "HORIZONTAL_GRAIN")]
public string HORIZONTAL_GRAIN { get; set; }
[XmlElement(ElementName = "PANEL_TYPE")]
public string PANEL_TYPE { get; set; }
[XmlElement(ElementName = "PANEL_EDGE")]
public string PANEL_EDGE { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE")]
public string PROFILED_EDGE { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_FRONT")]
public string PROFILED_EDGE_FRONT { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_BACK")]
public string PROFILED_EDGE_BACK { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_LEFT")]
public string PROFILED_EDGE_LEFT { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_RIGHT")]
public string PROFILED_EDGE_RIGHT { get; set; }
[XmlElement(ElementName = "EDGE_TYPE")]
public string EDGE_TYPE { get; set; }
[XmlElement(ElementName = "ANGLES_REQUIRED")]
public string ANGLES_REQUIRED { get; set; }
[XmlElement(ElementName = "ANGLE_LENGTH")]
public string ANGLE_LENGTH { get; set; }
[XmlElement(ElementName = "ANGLE_DEPTH")]
public string ANGLE_DEPTH { get; set; }
[XmlElement(ElementName = "THICKNESS")]
public string THICKNESS { get; set; }
[XmlElement(ElementName = "REVERSE_COLOUR")]
public string REVERSE_COLOUR { get; set; }
}
[XmlRoot(ElementName = "DELIVERY_ADDRESS")]
public class DELIVERY_ADDRESS
{
[XmlElement(ElementName = "ADDRESS1")]
public string ADDRESS1 { get; set; }
[XmlElement(ElementName = "ADDRESS2")]
public string ADDRESS2 { get; set; }
[XmlElement(ElementName = "TOWN")]
public string TOWN { get; set; }
[XmlElement(ElementName = "POSTCODE")]
public string POSTCODE { get; set; }
[XmlElement(ElementName = "COUNTY")]
public string COUNTY { get; set; }
[XmlElement(ElementName = "COUNTRY")]
public string COUNTRY { get; set; }
}
[XmlRoot(ElementName = "ORDER")]
public class ORDER
{
[XmlElement(ElementName = "ORDER_ID")]
public string ORDER_ID { get; set; }
[XmlElement(ElementName = "ORDERED_BY")]
public string ORDERED_BY { get; set; }
[XmlElement(ElementName = "ORDER_REFERENCE")]
public string ORDER_REFERENCE { get; set; }
[XmlElement(ElementName = "CUSTOMER_ID")]
public string CUSTOMER_ID { get; set; }
[XmlElement(ElementName = "ACCOUNT_REFERENCE")]
public string ACCOUNT_REFERENCE { get; set; }
[XmlElement(ElementName = "ORDER_TYPE")]
public string ORDER_TYPE { get; set; }
[XmlElement(ElementName = "ORDER_RANGE")]
public string ORDER_RANGE { get; set; }
[XmlElement(ElementName = "ORDER_COLOUR")]
public string ORDER_COLOUR { get; set; }
[XmlElement(ElementName = "EDGE_TYPE")]
public string EDGE_TYPE { get; set; }
[XmlElement(ElementName = "REVERSE_COLOUR")]
public string REVERSE_COLOUR { get; set; }
[XmlElement(ElementName = "HORIZONTAL_GRAIN")]
public string HORIZONTAL_GRAIN { get; set; }
[XmlElement(ElementName = "HANDLE_TYPE")]
public string HANDLE_TYPE { get; set; }
[XmlElement(ElementName = "NOTES")]
public string NOTES { get; set; }
[XmlElement(ElementName = "ORDER_DATE")]
public string ORDER_DATE { get; set; }
[XmlElement(ElementName = "DELIVERY_DATE")]
public string DELIVERY_DATE { get; set; }
[XmlElement(ElementName = "ADDITIONAL_DELIVERY_INFO")]
public string ADDITIONAL_DELIVERY_INFO { get; set; }
[XmlElement(ElementName = "ORDER_ITEM")]
public List<ORDER_ITEM> ORDER_ITEM { get; set; }
[XmlElement(ElementName = "DELIVERY_ADDRESS")]
public DELIVERY_ADDRESS DELIVERY_ADDRESS { get; set; }
[XmlElement(ElementName = "DELIVERY_TYPE")]
public string DELIVERY_TYPE { get; set; }
[XmlElement(ElementName = "DELIVERY_PRICE")]
public string DELIVERY_PRICE { get; set; }
[XmlElement(ElementName = "DELIVERY_CODE")]
public string DELIVERY_CODE { get; set; }
[XmlElement(ElementName = "TOTAL_EX_VAT")]
public string TOTAL_EX_VAT { get; set; }
[XmlElement(ElementName = "TOTAL_INC_VAT")]
public string TOTAL_INC_VAT { get; set; }
[XmlElement(ElementName = "TOTAL_INC_DELIVERY")]
public string TOTAL_INC_DELIVERY { get; set; }
}
}
Although I didn't get the same error as you when I setup a test case using your code, I did get an error about "ORDER" being unexpected.
I then successfully deserialized the XML by specifying SalesOrderXml.ORDER as the root class, rather than SalesOrderXml.
XmlSerializer serializer = new XmlSerializer(typeof(SalesOrderXml.ORDER));
using (TextReader reader = new StringReader(testData))
{
var ob = (SalesOrderXml.ORDER)serializer.Deserialize(reader);
}
I set testData exactly the same as your pastebin string (with the spaces trimmed as per Renzo's comment), and my test case ran successfully.

Deserialized C# into ASP.NET MVC View

I have deserialized the XML Response from API, now I need to display the deserialized objects to list in ASP.NET MVC View.
XML Response:
<AvailabilityOutbound>...</AvailabilityOutbound>
<AvailabilityReturn>...</AvailabilityReturn>
</Availability>
Controller:
public ActionResult Create([Bind(Include="FlightId,Origin,Destination,DepartFromDate,DepartToDate,ReturnFromDate,ReturnToDate,AdultPax,ChildPax,Language")] FlightAvailibility flightavailibility)
{
if (ModelState.IsValid)
{
BookingServiceReference.BookingService newBooking= new BookingServiceReference.BookingService();
string xmlResult = string.Empty;
xmlResult = newBooking.FlightAvailability("TESTAPI", "TESTAPI", flightavailibility.Origin, flightavailibility.Destination,
flightavailibility.DepartFromDate, flightavailibility.DepartToDate, flightavailibility.ReturnFromDate, flightavailibility.ReturnToDate,
flightavailibility.AdultPax, flightavailibility.ChildPax, 0, 0, null, null, null, "NP");
// return this.Content(xmlResult, "text/xml");
XmlSerializer serializer = new XmlSerializer(typeof(Availability));
using (StringReader reader = new StringReader(xmlResult))
{
Availability deserialized = (Availability)serializer.Deserialize(reader);
ViewBag.NewList = deserialized;
return View(deserialized);
}
}
return RedirectToAction("Index");
}
and the Model for class.
namespace YetiAirlinesProjectDev.Models
{
[XmlRoot(ElementName = "AvailabilityFlight")]
public class AvailabilityFlight
{
[XmlElement(ElementName = "airline_rcd")]
public string Airline_rcd { get; set; }
[XmlElement(ElementName = "flight_number")]
public string Flight_number { get; set; }
[XmlElement(ElementName = "booking_class_rcd")]
public string Booking_class_rcd { get; set; }
[XmlElement(ElementName = "boarding_class_rcd")]
public string Boarding_class_rcd { get; set; }
[XmlElement(ElementName = "flight_id")]
public string Flight_id { get; set; }
[XmlElement(ElementName = "origin_rcd")]
public string Origin_rcd { get; set; }
[XmlElement(ElementName = "destination_rcd")]
public string Destination_rcd { get; set; }
[XmlElement(ElementName = "origin_name")]
public string Origin_name { get; set; }
[XmlElement(ElementName = "destination_name")]
public string Destination_name { get; set; }
[XmlElement(ElementName = "flight_status_rcd")]
public string Flight_status_rcd { get; set; }
[XmlElement(ElementName = "departure_date")]
public string Departure_date { get; set; }
[XmlElement(ElementName = "planned_departure_time")]
public string Planned_departure_time { get; set; }
[XmlElement(ElementName = "planned_arrival_time")]
public string Planned_arrival_time { get; set; }
[XmlElement(ElementName = "fare_id")]
public string Fare_id { get; set; }
[XmlElement(ElementName = "fare_code")]
public string Fare_code { get; set; }
[XmlElement(ElementName = "transit_points")]
public string Transit_points { get; set; }
[XmlElement(ElementName = "transit_points_name")]
public string Transit_points_name { get; set; }
[XmlElement(ElementName = "transit_flight_id")]
public string Transit_flight_id { get; set; }
[XmlElement(ElementName = "transit_booking_class_rcd")]
public string Transit_booking_class_rcd { get; set; }
[XmlElement(ElementName = "transit_boarding_class_rcd")]
public string Transit_boarding_class_rcd { get; set; }
[XmlElement(ElementName = "transit_airport_rcd")]
public string Transit_airport_rcd { get; set; }
[XmlElement(ElementName = "transit_departure_date")]
public string Transit_departure_date { get; set; }
[XmlElement(ElementName = "transit_planned_departure_time")]
public string Transit_planned_departure_time { get; set; }
[XmlElement(ElementName = "transit_planned_arrival_time")]
public string Transit_planned_arrival_time { get; set; }
[XmlElement(ElementName = "transit_fare_id")]
public string Transit_fare_id { get; set; }
[XmlElement(ElementName = "transit_name")]
public string Transit_name { get; set; }
[XmlElement(ElementName = "transit_waitlist_open_flag")]
public string Transit_waitlist_open_flag { get; set; }
[XmlElement(ElementName = "transit_airline_rcd")]
public string Transit_airline_rcd { get; set; }
[XmlElement(ElementName = "transit_flight_number")]
public string Transit_flight_number { get; set; }
[XmlElement(ElementName = "transit_flight_status_rcd")]
public string Transit_flight_status_rcd { get; set; }
[XmlElement(ElementName = "transit_flight_duration")]
public string Transit_flight_duration { get; set; }
[XmlElement(ElementName = "transit_class_open_flag")]
public string Transit_class_open_flag { get; set; }
[XmlElement(ElementName = "transit_nesting_string")]
public string Transit_nesting_string { get; set; }
[XmlElement(ElementName = "nesting_string")]
public string Nesting_string { get; set; }
[XmlElement(ElementName = "full_flight_flag")]
public string Full_flight_flag { get; set; }
[XmlElement(ElementName = "class_open_flag")]
public string Class_open_flag { get; set; }
[XmlElement(ElementName = "close_web_sales")]
public string Close_web_sales { get; set; }
[XmlElement(ElementName = "total_adult_fare")]
public string Total_adult_fare { get; set; }
[XmlElement(ElementName = "total_child_fare")]
public string Total_child_fare { get; set; }
[XmlElement(ElementName = "total_infant_fare")]
public string Total_infant_fare { get; set; }
[XmlElement(ElementName = "fare_column")]
public string Fare_column { get; set; }
[XmlElement(ElementName = "flight_comment")]
public string Flight_comment { get; set; }
[XmlElement(ElementName = "filter_logic_flag")]
public string Filter_logic_flag { get; set; }
[XmlElement(ElementName = "restriction_text")]
public string Restriction_text { get; set; }
[XmlElement(ElementName = "flight_duration")]
public string Flight_duration { get; set; }
[XmlElement(ElementName = "class_capacity")]
public string Class_capacity { get; set; }
[XmlElement(ElementName = "waitlist_open_flag")]
public string Waitlist_open_flag { get; set; }
[XmlElement(ElementName = "refundable_flag")]
public string Refundable_flag { get; set; }
[XmlElement(ElementName = "currency_rcd")]
public string Currency_rcd { get; set; }
[XmlElement(ElementName = "aircraft_type_rcd")]
public string Aircraft_type_rcd { get; set; }
[XmlElement(ElementName = "transit_aircraft_type_rcd")]
public string Transit_aircraft_type_rcd { get; set; }
[XmlElement(ElementName = "arrival_date")]
public string Arrival_date { get; set; }
[XmlElement(ElementName = "transit_arrival_date")]
public string Transit_arrival_date { get; set; }
[XmlElement(ElementName = "number_of_stops")]
public string Number_of_stops { get; set; }
[XmlElement(ElementName = "eticket_flag")]
public string Eticket_flag { get; set; }
[XmlElement(ElementName = "nest_seat_availabile")]
public string Nest_seat_availabile { get; set; }
[XmlElement(ElementName = "endorsement_text")]
public string Endorsement_text { get; set; }
}
[XmlRoot(ElementName = "AvailabilityOutbound")]
public class AvailabilityOutbound
{
[XmlElement(ElementName = "AvailabilityFlight")]
public List<AvailabilityFlight> AvailabilityFlight { get; set; }
}
[XmlRoot(ElementName = "AvailabilityReturn")]
public class AvailabilityReturn
{
[XmlElement(ElementName = "AvailabilityFlight")]
public List<AvailabilityFlight> AvailabilityFlight { get; set; }
}
[XmlRoot(ElementName = "Availability")]
public class Availability
{
[XmlElement(ElementName = "AvailabilityOutbound")]
public AvailabilityOutbound AvailabilityOutbound { get; set; }
[XmlElement(ElementName = "AvailabilityReturn")]
public AvailabilityReturn AvailabilityReturn { get; set; }
}
}
Model for FlightAvailibility:
public class FlightAvailibility
{
public int FlightId { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
public string DepartFromDate { get; set; }
public string DepartToDate { get; set; }
public string ReturnFromDate { get; set; }
public string ReturnToDate { get; set; }
public short AdultPax { get; set; }
public short ChildPax { get; set; }
public string Language { get; set; }
}
Controller:
public ActionResult Index()
{
return View();
}
I want to show the availability List In Index View:
Index.cshtml
I have deserialized the XML Response from API, now I need to display the deserialized objects to list in ASP.NET MVC View.
XML Response:
<AvailabilityOutbound>...</AvailabilityOutbound>
<AvailabilityReturn>...</AvailabilityReturn>
</Availability>
Controller:
public ActionResult Create([Bind(Include="FlightId,Origin,Destination,DepartFromDate,DepartToDate,ReturnFromDate,ReturnToDate,AdultPax,ChildPax,Language")] FlightAvailibility flightavailibility)
{
if (ModelState.IsValid)
{
BookingServiceReference.BookingService newBooking= new BookingServiceReference.BookingService();
string xmlResult = string.Empty;
xmlResult = newBooking.FlightAvailability("TESTAPI", "TESTAPI", flightavailibility.Origin, flightavailibility.Destination,
flightavailibility.DepartFromDate, flightavailibility.DepartToDate, flightavailibility.ReturnFromDate, flightavailibility.ReturnToDate,
flightavailibility.AdultPax, flightavailibility.ChildPax, 0, 0, null, null, null, "NP");
// return this.Content(xmlResult, "text/xml");
XmlSerializer serializer = new XmlSerializer(typeof(Availability));
using (StringReader reader = new StringReader(xmlResult))
{
Availability deserialized = (Availability)serializer.Deserialize(reader);
ViewBag.NewList = deserialized;
return View(deserialized);
}
}
return RedirectToAction("Index");
}
and the Model for class.
namespace YetiAirlinesProjectDev.Models
{
[XmlRoot(ElementName = "AvailabilityFlight")]
public class AvailabilityFlight
{
[XmlElement(ElementName = "airline_rcd")]
public string Airline_rcd { get; set; }
[XmlElement(ElementName = "flight_number")]
public string Flight_number { get; set; }
[XmlElement(ElementName = "booking_class_rcd")]
public string Booking_class_rcd { get; set; }
[XmlElement(ElementName = "boarding_class_rcd")]
public string Boarding_class_rcd { get; set; }
[XmlElement(ElementName = "flight_id")]
public string Flight_id { get; set; }
[XmlElement(ElementName = "origin_rcd")]
public string Origin_rcd { get; set; }
[XmlElement(ElementName = "destination_rcd")]
public string Destination_rcd { get; set; }
[XmlElement(ElementName = "origin_name")]
public string Origin_name { get; set; }
[XmlElement(ElementName = "destination_name")]
public string Destination_name { get; set; }
[XmlElement(ElementName = "flight_status_rcd")]
public string Flight_status_rcd { get; set; }
[XmlElement(ElementName = "departure_date")]
public string Departure_date { get; set; }
[XmlElement(ElementName = "planned_departure_time")]
public string Planned_departure_time { get; set; }
[XmlElement(ElementName = "planned_arrival_time")]
public string Planned_arrival_time { get; set; }
[XmlElement(ElementName = "fare_id")]
public string Fare_id { get; set; }
[XmlElement(ElementName = "fare_code")]
public string Fare_code { get; set; }
[XmlElement(ElementName = "transit_points")]
public string Transit_points { get; set; }
[XmlElement(ElementName = "transit_points_name")]
public string Transit_points_name { get; set; }
[XmlElement(ElementName = "transit_flight_id")]
public string Transit_flight_id { get; set; }
[XmlElement(ElementName = "transit_booking_class_rcd")]
public string Transit_booking_class_rcd { get; set; }
[XmlElement(ElementName = "transit_boarding_class_rcd")]
public string Transit_boarding_class_rcd { get; set; }
[XmlElement(ElementName = "transit_airport_rcd")]
public string Transit_airport_rcd { get; set; }
[XmlElement(ElementName = "transit_departure_date")]
public string Transit_departure_date { get; set; }
[XmlElement(ElementName = "transit_planned_departure_time")]
public string Transit_planned_departure_time { get; set; }
[XmlElement(ElementName = "transit_planned_arrival_time")]
public string Transit_planned_arrival_time { get; set; }
[XmlElement(ElementName = "transit_fare_id")]
public string Transit_fare_id { get; set; }
[XmlElement(ElementName = "transit_name")]
public string Transit_name { get; set; }
[XmlElement(ElementName = "transit_waitlist_open_flag")]
public string Transit_waitlist_open_flag { get; set; }
[XmlElement(ElementName = "transit_airline_rcd")]
public string Transit_airline_rcd { get; set; }
[XmlElement(ElementName = "transit_flight_number")]
public string Transit_flight_number { get; set; }
[XmlElement(ElementName = "transit_flight_status_rcd")]
public string Transit_flight_status_rcd { get; set; }
[XmlElement(ElementName = "transit_flight_duration")]
public string Transit_flight_duration { get; set; }
[XmlElement(ElementName = "transit_class_open_flag")]
public string Transit_class_open_flag { get; set; }
[XmlElement(ElementName = "transit_nesting_string")]
public string Transit_nesting_string { get; set; }
[XmlElement(ElementName = "nesting_string")]
public string Nesting_string { get; set; }
[XmlElement(ElementName = "full_flight_flag")]
public string Full_flight_flag { get; set; }
[XmlElement(ElementName = "class_open_flag")]
public string Class_open_flag { get; set; }
[XmlElement(ElementName = "close_web_sales")]
public string Close_web_sales { get; set; }
[XmlElement(ElementName = "total_adult_fare")]
public string Total_adult_fare { get; set; }
[XmlElement(ElementName = "total_child_fare")]
public string Total_child_fare { get; set; }
[XmlElement(ElementName = "total_infant_fare")]
public string Total_infant_fare { get; set; }
[XmlElement(ElementName = "fare_column")]
public string Fare_column { get; set; }
[XmlElement(ElementName = "flight_comment")]
public string Flight_comment { get; set; }
[XmlElement(ElementName = "filter_logic_flag")]
public string Filter_logic_flag { get; set; }
[XmlElement(ElementName = "restriction_text")]
public string Restriction_text { get; set; }
[XmlElement(ElementName = "flight_duration")]
public string Flight_duration { get; set; }
[XmlElement(ElementName = "class_capacity")]
public string Class_capacity { get; set; }
[XmlElement(ElementName = "waitlist_open_flag")]
public string Waitlist_open_flag { get; set; }
[XmlElement(ElementName = "refundable_flag")]
public string Refundable_flag { get; set; }
[XmlElement(ElementName = "currency_rcd")]
public string Currency_rcd { get; set; }
[XmlElement(ElementName = "aircraft_type_rcd")]
public string Aircraft_type_rcd { get; set; }
[XmlElement(ElementName = "transit_aircraft_type_rcd")]
public string Transit_aircraft_type_rcd { get; set; }
[XmlElement(ElementName = "arrival_date")]
public string Arrival_date { get; set; }
[XmlElement(ElementName = "transit_arrival_date")]
public string Transit_arrival_date { get; set; }
[XmlElement(ElementName = "number_of_stops")]
public string Number_of_stops { get; set; }
[XmlElement(ElementName = "eticket_flag")]
public string Eticket_flag { get; set; }
[XmlElement(ElementName = "nest_seat_availabile")]
public string Nest_seat_availabile { get; set; }
[XmlElement(ElementName = "endorsement_text")]
public string Endorsement_text { get; set; }
}
[XmlRoot(ElementName = "AvailabilityOutbound")]
public class AvailabilityOutbound
{
[XmlElement(ElementName = "AvailabilityFlight")]
public List<AvailabilityFlight> AvailabilityFlight { get; set; }
}
[XmlRoot(ElementName = "AvailabilityReturn")]
public class AvailabilityReturn
{
[XmlElement(ElementName = "AvailabilityFlight")]
public List<AvailabilityFlight> AvailabilityFlight { get; set; }
}
[XmlRoot(ElementName = "Availability")]
public class Availability
{
[XmlElement(ElementName = "AvailabilityOutbound")]
public AvailabilityOutbound AvailabilityOutbound { get; set; }
[XmlElement(ElementName = "AvailabilityReturn")]
public AvailabilityReturn AvailabilityReturn { get; set; }
}
}
Model for FlightAvailibility:
public class FlightAvailibility
{
public int FlightId { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
public string DepartFromDate { get; set; }
public string DepartToDate { get; set; }
public string ReturnFromDate { get; set; }
public string ReturnToDate { get; set; }
public short AdultPax { get; set; }
public short ChildPax { get; set; }
public string Language { get; set; }
}
Controller:
public ActionResult Index()
{
return View();
}
I want to show the availability List In Index View:
Index.cshtml
#model {YetiAirlinesProjectDev.Models.Availability objnew = (YetiAirlinesProjectDev.Models.Availability)ViewBag.NewList}
<table class="table">
<tr>
<th>
#Html.Display("Aircraft Name")
</th>
</tr>
#foreach (var item in objnew) {
<tr>
<td>
#item
</td>
</tr>
}
</table>
I need to represent the list of availability: AvailabilityOutbound & AvailabilityReturn using Viewbag in Asp.Net MVC View i.e Index Page. I get difficulty passing the Viewbag contents to View i.e Index. My code is not workable in View. I tried a lot. Please help me guys.
First you get you data from api in xml format and then JavaScriptSerializer and make class to pass data to model.In this code the rentlisting action get list from api and show on the view pass list to the view in GetRentListing() function get the api data and last class show they convert the api data to class object and show in view model.
public ActionResult RentListing()
{
if (Session["rentlist"] != null)
{
var list = (List<RootObject>)Session["rentlist"];
return View(list);
}
else
{
var value = GetRentListing();
var list = (List<RootObject>)Session["rentlist"];
return View(list);
}
}
[HttpGet]
public async System.Threading.Tasks.Task<string> GetRentListing()
{
try
{
HttpClient client = new HttpClient();
string AccessCode = ConfigurationManager.AppSettings["AccessCode"];
string GroupCode = ConfigurationManager.AppSettings["GroupCode"];
string Url = "http://www.airlist.com/v1.1/website.asmx/RentListings?AccessCode=" + AccessCode + "&GroupCode=" + GroupCode + "&unitId=" + "" + "&StartPriceRange=" + "" + "&EndPriceRange=" + "" + "&floorAreaMin=" + "" + "&floorAreaMax=" + "" + "&cityId=" + "" + "&unitTypeId=" + "" + "&BedroomsMin=" + "" + "&BedroomsMax=" + "" + "&CommunityId=" + "" + "";
client.BaseAddress = new Uri(Url);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(Url).Result;
string data = "false";
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsStringAsync();
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc);
var list = new JavaScriptSerializer().Deserialize<dynamic>(json);
var d = ((list["RentListings"])["RentListing"]);
var lists = new JavaScriptSerializer().Serialize(d);
lists = lists.Replace("#cdata-section", "cdata");
var listss = new JavaScriptSerializer().Deserialize<List<RootObject>>(lists);
Session["rentlist"] = listss;
}
return data;
}
catch (Exception e)
{
throw;
}
}
public class RootObject
{
public string Count { get; set; }
public string Country { get; set; }
public object State { get; set; }
public string City { get; set; }
public object District { get; set; }
}

Error parsing JSON with NewtonSoft

Merry Christmas stackies! I'm trying to parse some JSON from the Wunderground weather API and I'm running into an issue when trying to assign values to variables. Here is a link to the JSON. Just know that the class structure I'm providing is a conglomerate in order to accommodate multiple JSON return file structures. I'll give the class structre, then the call from main, and finally the actual method with the error notated. I'm working in Xamarin, formerlly MonoDevelop. Thanks for anything you can come up with!
The error reads:
Newtonsoft.Json.JsonReaderException has been thrown
"Cannot convert String to Integer: 5.0 Path
'current_observation.wind_gust_mph', line 60, position 24.
public class Wunder
{
//constructor
public Wunder ()
{
}
//JSON classes
public class HistoryResponseContainer
{
public ResponseInfo response { get; set; }
public HistoryInfo history { get; set; }
public Location location { get; set; }
public CurrentObservation current_observation { get; set; }
}
public class ResponseInfo
{
public string version { get; set; }
public string termsofService { get; set; }
public Dictionary<string, int> features { get; set; }
}
public class HistoryInfo
{
public WUDate date { get; set; }
public WUDate utcdate { get; set; }
public Observation[] observations { get; set; }
public Dailysummary[] dailysummary { get; set; }
}
public class WUDate
{
public string pretty { get; set; }
public string year { get; set; }
public string mon { get; set; }
public string mday { get; set; }
public string hour { get; set; }
public string min { get; set; }
public string tzname { get; set; }
public DateTime Value
{
get
{
int year = int.Parse(this.year);
int month = int.Parse(this.mon);
int day = int.Parse(this.mday);
int hour = int.Parse(this.hour);
int minute = int.Parse(this.min);
var kind = this.tzname == "UTC"
? DateTimeKind.Utc
: DateTimeKind.Unspecified;
return new DateTime(year, month, day, hour, minute, 0, kind);
}
}
}
public class Observation
{
public WUDate date { get; set; }
public WUDate utcdate { get; set; }
public string tempm { get; set; }
public string tempi { get; set; }
public string dewptm { get; set; }
public string dewpti { get; set; }
public string hum { get; set; }
public string wspdm { get; set; }
public string wspdi { get; set; }
public string wgustm { get; set; }
public string wgusti { get; set; }
public string wdird { get; set; }
public string wdire { get; set; }
public string vism { get; set; }
public string visi { get; set; }
public string pressurem { get; set; }
public string pressurei { get; set; }
public string windchillm { get; set; }
public string windchilli { get; set; }
public string heatindexm { get; set; }
public string heatindexi { get; set; }
public string precipm { get; set; }
public string precipi { get; set; }
public string conds { get; set; }
public string icon { get; set; }
public string fog { get; set; }
public string rain { get; set; }
public string snow { get; set; }
public string hail { get; set; }
public string thunder { get; set; }
public string tornado { get; set; }
public string metar { get; set; }
}
public class Dailysummary
{
public WUDate date { get; set; }
public string fog { get; set; }
public string rain { get; set; }
public string snow { get; set; }
public string snowfallm { get; set; }
public string snowfalli { get; set; }
public string monthtodatesnowfallm { get; set; }
public string monthtodatesnowfalli { get; set; }
public string since1julsnowfallm { get; set; }
public string since1julsnowfalli { get; set; }
public string snowdepthm { get; set; }
public string snowdepthi { get; set; }
public string hail { get; set; }
public string thunder { get; set; }
public string tornado { get; set; }
public string meantempm { get; set; }
public string meantempi { get; set; }
public string meandewptm { get; set; }
public string meandewpti { get; set; }
public string meanpressurem { get; set; }
public string meanpressurei { get; set; }
public string meanwindspdm { get; set; }
public string meanwindspdi { get; set; }
public string meanwdire { get; set; }
public string meanwdird { get; set; }
public string meanvism { get; set; }
public string meanvisi { get; set; }
public string humidity { get; set; }
public string maxtempm { get; set; }
public string maxtempi { get; set; }
public string mintempm { get; set; }
public string mintempi { get; set; }
public string maxhumidity { get; set; }
public string minhumidity { get; set; }
public string maxdewptm { get; set; }
public string maxdewpti { get; set; }
public string mindewptm { get; set; }
public string mindewpti { get; set; }
public string maxpressurem { get; set; }
public string maxpressurei { get; set; }
public string minpressurem { get; set; }
public string minpressurei { get; set; }
public string maxwspdm { get; set; }
public string maxwspdi { get; set; }
public string minwspdm { get; set; }
public string minwspdi { get; set; }
public string maxvism { get; set; }
public string maxvisi { get; set; }
public string minvism { get; set; }
public string minvisi { get; set; }
public string gdegreedays { get; set; }
public string heatingdegreedays { get; set; }
public string coolingdegreedays { get; set; }
public string precipm { get; set; }
public string precipi { get; set; }
public string precipsource { get; set; }
public string heatingdegreedaysnormal { get; set; }
public string monthtodateheatingdegreedays { get; set; }
public string monthtodateheatingdegreedaysnormal { get; set; }
public string since1sepheatingdegreedays { get; set; }
public string since1sepheatingdegreedaysnormal { get; set; }
public string since1julheatingdegreedays { get; set; }
public string since1julheatingdegreedaysnormal { get; set; }
public string coolingdegreedaysnormal { get; set; }
public string monthtodatecoolingdegreedays { get; set; }
public string monthtodatecoolingdegreedaysnormal { get; set; }
public string since1sepcoolingdegreedays { get; set; }
public string since1sepcoolingdegreedaysnormal { get; set; }
public string since1jancoolingdegreedays { get; set; }
public string since1jancoolingdegreedaysnormal { get; set; }
}
public class Station
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
public string icao { get; set; }
public string lat { get; set; }
public string lon { get; set; }
}
public class Airport
{
public List<Station> station { get; set; }
}
public class Station2
{
public string neighborhood { get; set; }
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
public string id { get; set; }
public double lat { get; set; }
public double lon { get; set; }
public int distance_km { get; set; }
public int distance_mi { get; set; }
}
public class Pws
{
public List<Station2> station { get; set; }
}
public class NearbyWeatherStations
{
public Airport airport { get; set; }
public Pws pws { get; set; }
}
public class Location
{
public string type { get; set; }
public string country { get; set; }
public string country_iso3166 { get; set; }
public string country_name { get; set; }
public string state { get; set; }
public string city { get; set; }
public string tz_short { get; set; }
public string tz_long { get; set; }
public string lat { get; set; }
public string lon { get; set; }
public string zip { get; set; }
public string magic { get; set; }
public string wmo { get; set; }
public string l { get; set; }
public string requesturl { get; set; }
public string wuiurl { get; set; }
public NearbyWeatherStations nearby_weather_stations { get; set; }
}
public class CurrentObservation
{
public Image image { get; set; }
public DisplayLocation display_location { get; set; }
public ObservationLocation observation_location { get; set; }
public Estimated estimated { get; set; }
public string station_id { get; set; }
public string observation_time { get; set; }
public string observation_time_rfc822 { get; set; }
public string observation_epoch { get; set; }
public string local_time_rfc822 { get; set; }
public string local_epoch { get; set; }
public string local_tz_short { get; set; }
public string local_tz_long { get; set; }
public string local_tz_offset { get; set; }
public string weather { get; set; }
public string temperature_string { get; set; }
public double temp_f { get; set; }
public double temp_c { get; set; }
public string relative_humidity { get; set; }
public string wind_string { get; set; }
public string wind_dir { get; set; }
public int wind_degrees { get; set; }
public double wind_mph { get; set; }
public int wind_gust_mph { get; set; }
public int wind_kph { get; set; }
public int wind_gust_kph { get; set; }
public string pressure_mb { get; set; }
public string pressure_in { get; set; }
public string pressure_trend { get; set; }
public string dewpoint_string { get; set; }
public int dewpoint_f { get; set; }
public int dewpoint_c { get; set; }
public string heat_index_string { get; set; }
public string heat_index_f { get; set; }
public string heat_index_c { get; set; }
public string windchill_string { get; set; }
public string windchill_f { get; set; }
public string windchill_c { get; set; }
public string feelslike_string { get; set; }
public string feelslike_f { get; set; }
public string feelslike_c { get; set; }
public string visibility_mi { get; set; }
public string visibility_km { get; set; }
public string solarradiation { get; set; }
public string UV { get; set; }
public string precip_1hr_string { get; set; }
public string precip_1hr_in { get; set; }
public string precip_1hr_metric { get; set; }
public string precip_today_string { get; set; }
public string precip_today_in { get; set; }
public string precip_today_metric { get; set; }
public string icon { get; set; }
public string icon_url { get; set; }
public string forecast_url { get; set; }
public string history_url { get; set; }
public string ob_url { get; set; }
}
public class ObservationLocation
{
public string full { get; set; }
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
public string country_iso3166 { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string elevation { get; set; }
}
public class Image
{
public string url { get; set; }
public string title { get; set; }
public string link { get; set; }
}
public class DisplayLocation
{
public string full { get; set; }
public string city { get; set; }
public string state { get; set; }
public string state_name { get; set; }
public string country { get; set; }
public string country_iso3166 { get; set; }
public string zip { get; set; }
public string magic { get; set; }
public string wmo { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string elevation { get; set; }
}
public class Estimated
{
}
And here is the call from main.
class MainClass
{
public static void Main (string[] args)
{
Wunder data = new Wunder ();
string StationID = "KCOBOULD67";
string CurrentConditions = data.GetCurrentConditions (StationID);
Console.WriteLine (CurrentConditions);
}
}
Lastly, this is the method being called. I took out my Wunderground Key. If you want an example of the return JSON, check the link at the top.
public String GetCurrentConditions(string StationID){
String url = #"http://api.wunderground.com/api/" + wundergroundkey + "/conditions/q/pws:" + StationID + ".json";
Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse response = webRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
String responseData = streamReader.ReadToEnd();
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
String stationid = container.current_observation.station_id;
String station_lat = container.current_observation.observation_location.latitude;
String station_lon = container.current_observation.observation_location.longitude;
String station_data = stationid + station_lat + station_lon;
return (station_data);
} //End GetCurrentConditions
Again, the error reads:
Newtonsoft.Json.JsonReaderException has been thrown
"Cannot convert String to Integer: 5.0 Path
'current_observation.wind_gust_mph', line 60, position 24.
You provided us a link to the following JSON:
http://api.wunderground.com/api/21fd5aec70326254/conditions/q/CA/San_Francisco.json
As you see there, the property wind_gust_mph is 0 (without the quotes, so an Integer). This JSON also works very well. But in your code you use the following JSON:
http://api.wunderground.com/api/21fd5aec70326254/conditions/q/pws:KCOBOULD67.json
And there the property wind_gust_mph is "4.0" (with the quotes, so a String). And you cannot parse a string property into an integer. Also the properties for wind_kph and wind_gust_kph are wrong, this should be either string or double:
public string wind_gust_mph { get; set; }
public double wind_kph { get; set; }
public string wind_gust_kph { get; set; }
Hope this helps and merry x-mas.

Categories