Grabbing Json Data to String in Gridview - c#

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

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
}

Getting specific data from JSON Model

Here is my JSON model for trying to get info from Google Maps API. I am trying to get the "name" and "vicinity" from the "Result "class, but am having trouble with getting the data values from the IList, preferably i would like all the name and vicinity attributes to be returned as a string. Anyone got any ideas? Not familiar with using IList's on projects.
public record Location
{
public double lat { get; set; }
public double lng { get; set; }
}
public record Northeast
{
public double lat { get; set; }
public double lng { get; set; }
}
public record Southwest
{
public double lat { get; set; }
public double lng { get; set; }
}
public record Viewport
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
public record Geometry
{
public Location location { get; set; }
public Viewport viewport { get; set; }
}
public record OpeningHours
{
public bool? open_now { get; set; }
}
public record Photo
{
public int height { get; set; }
public IList<string> html_attributions { get; set; }
public string photo_reference { get; set; }
public int width { get; set; }
}
public record PlusCode
{
public string compound_code { get; set; }
public string global_code { get; set; }
}
public record Result
{
public string business_status { get; set; }
public Geometry geometry { get; set; }
public string icon { get; set; }
public string icon_background_color { get; set; }
public string icon_mask_base_uri { get; set; }
public string name { get; set; }
public OpeningHours opening_hours { get; set; }
public IList<Photo> photos { get; set; }
public string place_id { get; set; }
public PlusCode plus_code { get; set; }
public double rating { get; set; }
public string reference { get; set; }
public string scope { get; set; }
public IList<string> types { get; set; }
public int user_ratings_total { get; set; }
public string vicinity { get; set; }
}
public record ResourceData
{
public IList<object> html_attributions { get; set; }
public IList<Result> results { get; set; }
public string status { get; set; }
}
public record record_GooglePlacesAPI
{
public DateTime TimeCreated { get; set; } = DateTime.UtcNow;
public ResourceData resourceData { get; set; }
}
Try running a simple LINQ query on the data returned from google API like the following
//string holding google api response
string googleResponse = string.Empty;
var googleapi = JsonConvert.DeserializeObject<record_GooglePlacesAPI>(googleResponse);
//Linq query that returns list of names and vicinities
List<string> vicinities = googleapi.resourceData.results.Select(r => r.vicinity).ToList();
List<string> names = googleapi.resourceData.results.Select(r => r.name).ToList();
it should return you a list of strings holding names and viciniteis

Incorrect JSON Output Using ASP.NET

Please excuse this question as a sign of frustration. While I understand that cause of the issue is the converting of data into different types, I can't put my finger on what's causing the result of this web service get method to be output incorrectly, that is containing backslashes.
The code below sums up the functionality of my method. I've tried different suggestions I found on these forums, some of which were in reply to similar questions I asked myself.
Data Model
public class WeatherResponse
{
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 int temp_min { get; set; }
public int temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public int 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<WeatherResponse> 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; }
}
}
Controller
[HttpGet]
public string Get(string city, string country)
{
string apiKey = "KEY";
HttpWebRequest apiRequest = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + country + " &appid=" + apiKey + "&units=metric") as HttpWebRequest;
string apiResponse = "";
using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
apiResponse = reader.ReadToEnd();
}
Response.ContentType = "application/json";
return apiResponse;
}
Result
"{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":521,\"main\":\"Rain\",\"description\":\"shower
rain\",\"icon\":\"09d\"}],\"base\":\"stations\",\"main\":{\"temp\":2.62,\"pressure\":991,\"humidity\":69,\"temp_min\":1,\"temp_max\":4},\"visibility\":10000,\"wind\":{\"speed\":5.1,\"deg\":90},\"clouds\":{\"all\":75},\"dt\":1548939000,\"sys\":{\"type\":1,\"id\":1414,\"message\":0.0037,\"country\":\"GB\",\"sunrise\":1548920401,\"sunset\":1548953318},\"id\":2643743,\"name\":\"London\",\"cod\":200}"
I need the code to simply retrieve weather data using the city and country received and correctly output it as JSON.
Here's the solution to the problem, as kindly posted by Joroen Mostert.
You should be able to use Content for this (when you change the return
type of your method to IActionResult): return Content(apiResponse,
"application/json") should not further escape.

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.

get data from json c#

I have a problem I want to get data from Json, and the data
successfully gets from the json to the variable json but when I want to send the data to WeatherData it send me a zero value.
I have one class that cald "WeatherData" and I want to send to data from the json (that existing a class "jsonParse") to this class.
jsonParse
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.Script.Serialization;
using System.IO;
namespace weather
{
public class jsonParse : Ijson
{
private string urlAdd;
public jsonParse(string _url)
{
if (_url == null)
{
//throw exption
}
else
urlAdd = _url;
}
public WeatherData parse()
{
//string json = new WebClient().DownloadString(urlAdd);
//var obj = JsonConvert.DeserializeObject<WeatherData>(json);
//Console.WriteLine(obj.temp);
// WeatherData m = JsonConvert.DeserializeObject<WeatherData>(json);
WebClient n = new WebClient();
var json = n.DownloadString(urlAdd);
string valueOriginal = Convert.ToString(json);
WeatherData m = JsonConvert.DeserializeObject<WeatherData>(json);
Console.WriteLine(m);
return m;
}
}
}
WeatherData
namespace weather
{
public class WeatherData
{
public WeatherData(double _temp, double _minTemp, double _maxTemp )
{
temp = _temp;
minTemp = _minTemp;
maxTemp = _maxTemp;
}
public double temp { get; set; }
public double minTemp { get; set; }
public double maxTemp { get; set; }
public override string ToString()
{
return "the weather:" + temp + "minTemp is:" + minTemp + "maxTemp:" + maxTemp;
}
}
}
json
{"coord":{"lon":139,"lat":35},
"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
"weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
"main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
"wind":{"speed":7.31,"deg":187.002},
"rain":{"3h":0},
"clouds":{"all":92},
"dt":1369824698,
"id":1851632,
"name":"Shuzenji",
"cod":200}
If you only care about the weather part of the json, try this -
var o = (JArray)JObject.Parse(jsonString)["weather"];
foreach(JToken item in o)
{
Console.WriteLine(((JValue)item["id"]).Value);
Console.WriteLine(((JValue)item["main"]).Value);
Console.WriteLine(((JValue)item["description"]).Value);
Console.WriteLine(((JValue)item["icon"]).Value);
}
First object in json is coord, don't see that in your model.
You should change your JsonModel to deserialize. From c# class generator:
public class Coord
{
public int lon { get; set; }
public int lat { get; set; }
}
public class Sys
{
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { 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 humidity { get; set; }
public int pressure { 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 Rain
{
public int __invalid_name__3h { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class RootObject
{
public Coord coord { get; set; }
public Sys sys { get; set; }
public List<Weather> weather { get; set; }
public Main main { get; set; }
public Wind wind { get; set; }
public Rain rain { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
Where RootObject is your JsonConvert.DeserializeObject(json);
So you can change class names as you like.
Simply you cannot Deserialize a json object to a non-matching class object. So make sure you have a model object that have atleast all the properties that JSON object have.
In this case you would need following classes that are generated from your JSON object:
public class Coord
{
public int lon { get; set; }
public int lat { get; set; }
}
public class Sys
{
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { 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 humidity { get; set; }
public int pressure { 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 Rain
{
public int __invalid_name__3h { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class ParentModel
{
public Coord coord { get; set; }
public Sys sys { get; set; }
public List<Weather> weather { get; set; }
public Main main { get; set; }
public Wind wind { get; set; }
public Rain rain { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
ParentModel m = JsonConvert.DeserializeObject<ParentModel>(json);
Hope this helps.

Categories

Resources