C# JSON Get data from List<> - c#

I am trying to make simple UWP weather app, just for learning purpose, and I am having trouble getting data from JSON.
How to get min and max temperature from public class ConsolidatedWeather?
I can get data from other classes.
Thanks a lot
Vrime.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace _01_Weaather
{
class Vrime
{
public async static Task<ConsolidatedWeather> ShowTemp()
{
var http = new HttpClient();
var url = String.Format("https://www.metaweather.com/api/location/44418/");
var response = await http.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
var ser = new DataContractJsonSerializer(typeof(ConsolidatedWeather));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (ConsolidatedWeather)ser.ReadObject(ms);
return data;
}
}
[DataContract]
public class ConsolidatedWeather
{
[DataMember]
public object id { get; set; }
[DataMember]
public string weather_state_name { get; set; }
[DataMember]
public string weather_state_abbr { get; set; }
[DataMember]
public string wind_direction_compass { get; set; }
[DataMember]
public string created { get; set; }
[DataMember]
public string applicable_date { get; set; }
[DataMember]
public double min_temp { get; set; }
[DataMember]
public double max_temp { get; set; }
[DataMember]
public double the_temp { get; set; }
[DataMember]
public double wind_speed { get; set; }
[DataMember]
public double wind_direction { get; set; }
[DataMember]
public double air_pressure { get; set; }
[DataMember]
public int humidity { get; set; }
[DataMember]
public double? visibility { get; set; }
[DataMember]
public int predictability { get; set; }
}
[DataContract]
public class Parent
{
[DataMember]
public string title { get; set; }
[DataMember]
public string location_type { get; set; }
[DataMember]
public int woeid { get; set; }
[DataMember]
public string latt_long { get; set; }
}
[DataContract]
public class Source
{
[DataMember]
public string title { get; set; }
[DataMember]
public string slug { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public int crawl_rate { get; set; }
}
[DataContract]
public class RootObject
{[DataMember]
public List<ConsolidatedWeather> consolidated_weather { get; set; }
[DataMember]
public string time { get; set; }
[DataMember]
public string sun_rise { get; set; }
[DataMember]
public string sun_set { get; set; }
[DataMember]
public string timezone_name { get; set; }
[DataMember]
public Parent parent { get; set; }
[DataMember]
public List<Source> sources { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string location_type { get; set; }
[DataMember]
public int woeid { get; set; }
[DataMember]
public string latt_long { get; set; }
[DataMember]
public string timezone { get; set; }
}
MainPage.xaml
namespace _01_Weaather
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
double min;
double max;
public MainPage()
{
this.InitializeComponent();
}
private async void BtnPrikaz_OnClick(object sender, RoutedEventArgs e)
{
ConsolidatedWeather cWeather = await Vrime.ShowTemp();
min =cWeather.min_temp;
max = cWeather.max_temp;
txtTemp.Text = String.Format(min.ToString() + "\n"+ max.ToString());
}
}

Your deserializing is not on the correct object. It should be on RootObject. As the JSON retured by weather API returns data for future dates as well so if you need Min and Max temperature for today then below is the sample code.
public async Task<RootObject> ShowTemp()
{
var http = new HttpClient();
var url = String.Format("https://www.metaweather.com/api/location/44418/");
var response = await http.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
var ser = new DataContractJsonSerializer(typeof(RootObject));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (RootObject)ser.ReadObject(ms);
return data;
}
public async Task<ConsolidatedWeather> GetWeatherForToday()
{
RootObject ro = await ShowTemp();
ConsolidatedWeather todayWeather = ro.consolidated_weather.FirstOrDefault();
return todayWeather;
// for getting min and max
// todayWeather.min_temp;
// todayWeather.max_temp;
}

try changing the data types of the attributes min & max temperature to float and you are using wrong object type to deserialize. use your root object. Also, i'd recommend using something like restsharp for api consumption. thats going to make your life 2X easier.

Related

UWP Get array from json Url

I'm using a class to get data from json to my main page and in my json i have an array i want to get them to my Main Page Here's my class code
class WeatherDays
{
public async static Task<day> GetWeather(double lat, double lon)
{
var http = new HttpClient();
var responce = await http.GetAsync("http://a3ane.com/omarNasar/d.php");
var result = await responce.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(day));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (day)serializer.ReadObject(ms);
return data;
}
}
[DataContract]
public class Omarnasar
{
[DataMember]
public string w_id { get; set; }
[DataMember]
public string w_note_tody { get; set; }
[DataMember]
public string w_date { get; set; }
[DataMember]
public string w_time { get; set; }
[DataMember]
public string w_tody_one { get; set; }
[DataMember]
public string w_temperature_one { get; set; }
[DataMember]
public string w_humidity_one { get; set; }
[DataMember]
public string w_note_one { get; set; }
[DataMember]
public string w_tody_two { get; set; }
[DataMember]
public string w_temperature_two { get; set; }
[DataMember]
public string w_humidity_two { get; set; }
[DataMember]
public string w_note_two { get; set; }
[DataMember]
}
[DataContract]
public class day
{
[DataMember]
public List<Omarnasar> omarnasar { get; set; }
}
}
and my problem is i don't know how to get then to my main page using the task here's my try on MainPage
day week = await WeatherDays.GetWeather(20.0, 30.0);
temp1.Text = week.omarnasr.
I don't know how to use them can anyone help my !!!
I think this is what you want
StringBuilder sb = new StringBuilder();
foreach(var obj in week.omarnasr)
{
sb.Append(obj.w_temperature_one + " ");
}
temp1.Text = sb.ToString();

Response is null when I used Restsharp library's GET request to access Json data

I am using Restsharp library to do Webservice operations.I tried to access data from the link(http://www.mocky.io/v2/595616d92900003d02cd7191) and print it in Console but I am not getting any response.When I used breakpoints,Response is showing null.Here's my code to get data from the link.
private async void GetItemsFromJSON()
{
IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
IRestRequest request = new RestRequest(Method.GET);
request.RequestFormat = DataFormat.Json;
try
{
await Task.Run(() =>
{
IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
Console.WriteLine(response.Content);
}
public class ItemDetails
{
public List<Itemschema> items { get; set; }
}
public class Itemschema
{
public int id { get; set; }
public string sku { get; set; }
public string name { get; set; }
public int attribute_set_id { get; set; }
public int price { get; set; }
public int status { get; set; }
public int visibility { get; set; }
public string type_id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public int weight { get; set; }
}
Am I missing something here?My schema class which corresponds to the Json data is shown above.
I suspect that:
IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
should be:
IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
http://www.mocky.io/v2/595616d92900003d02cd7191 seems to return an items property which contains an array of schemas. That maps closer to ItemDetails than List<ItemDetails>.
This complete sample works, so you may want to compare it with your code:
using System;
using System.Collections.Generic;
using RestSharp;
namespace Test
{
public class ItemDetails
{
public List<Itemschema> items { get; set; }
}
public class Itemschema
{
public int id { get; set; }
public string sku { get; set; }
public string name { get; set; }
public int attribute_set_id { get; set; }
public int price { get; set; }
public int status { get; set; }
public int visibility { get; set; }
public string type_id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public int weight { get; set; }
}
public class Program
{
static void Main(string[] args)
{
IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
IRestRequest request = new RestRequest(Method.GET);
request.RequestFormat = DataFormat.Json;
IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
Console.WriteLine(Items.items.Count);
Console.ReadLine();
}
}
}

C# Beginner - Using classes in different from different classes

This is a file called TwitchAPIexample in folder Plugins under project MyFirstBot. The classes and code is below:
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace MyFirstBot.Plugins
{
public class TwitchAPIexample
{
private const string url = "https://api.twitch.tv/kraken/streams/<channel>";
public bool isTwitchLive;
private static void BuildConnect()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Get";
request.Timeout = 12000;
request.ContentType = "application/json";
request.Headers.Add("authorization", "<token>");
using (System.IO.Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
RootObject r = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
}
}
}
public class Preview
{
public string small { get; set; }
public string medium { get; set; }
public string large { get; set; }
public string template { get; set; }
}
public class Channel
{
public bool mature { get; set; }
public string status { get; set; }
public string broadcaster_language { get; set; }
public string display_name { get; set; }
public string game { get; set; }
public string language { get; set; }
public int _id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public bool partner { get; set; }
public string logo { get; set; }
public string video_banner { get; set; }
public string profile_banner { get; set; }
public object profile_banner_background_color { get; set; }
public string url { get; set; }
public int views { get; set; }
public int followers { get; set; }
}
public class Stream
{
public long _id { get; set; }
public string game { get; set; }
public int viewers { get; set; }
public int video_height { get; set; }
public int average_fps { get; set; }
public int delay { get; set; }
public string created_at { get; set; }
public bool is_playlist { get; set; }
public Preview preview { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Stream stream { get; set; }
}
}
}
What I need to do is use the classes in the namespace MyfirstBot.Plugins in a different file under MyFirstBot project file. I have:
using namespace MyFirstBot.Plugins
but I'm not sure how to use the RootObject. I have tried using:
TwitchAPIexample.stream TwitchLive = new TwitchAPIexample.stream()
but I dont really know how to go from there to check the other strings in the JSON, set them equal to strings, basically just how to manipulate everything in the TwitchAPIexample class.
Again I'm a C# Noob so you don't have to write it for me, but if you could explain it or hit me up with a good resource. I have googled and still am confused. OOP isnt my strong suit.
This is as far as I have gotten:
namespace MyFirstBot
{
public class DiscordBot
{
DiscordClient client;
CommandService commands;
TwitchClient TwitchClient;
TwitchAPIexample.Stream TwitchLive = new TwitchAPIexample.Stream();
public DiscordBot()
{
if(TwitchLive.equals(null))
{
//stream is offline
}
}
}
}
I'm not sure this is the best method.
For me it looks like you need to change your architecture a bit. You don't need static method, and you need to create property trough which you'd be able to access RootObject. And you don't really need to nest those classes.
public class TwitchAPIexample
{
private const string url = "https://api.twitch.tv/kraken/streams/<channel>";
public bool IsTwitchLive { get; set; }
public RootObject Root { get; set; }
public TwitchAPIexample()
{
BuildConnect();
}
private void BuildConnect()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Get";
request.Timeout = 12000;
request.ContentType = "application/json";
request.Headers.Add("authorization", "<token>");
using (System.IO.Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
this.Root = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
}
}
}
}
public class Preview
{
public string small { get; set; }
public string medium { get; set; }
public string large { get; set; }
public string template { get; set; }
}
public class Channel
{
public bool mature { get; set; }
public string status { get; set; }
public string broadcaster_language { get; set; }
public string display_name { get; set; }
public string game { get; set; }
public string language { get; set; }
public int _id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public bool partner { get; set; }
public string logo { get; set; }
public string video_banner { get; set; }
public string profile_banner { get; set; }
public object profile_banner_background_color { get; set; }
public string url { get; set; }
public int views { get; set; }
public int followers { get; set; }
}
public class Stream
{
public long _id { get; set; }
public string game { get; set; }
public int viewers { get; set; }
public int video_height { get; set; }
public int average_fps { get; set; }
public int delay { get; set; }
public string created_at { get; set; }
public bool is_playlist { get; set; }
public Preview preview { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Stream stream { get; set; }
}
Now you can do next
namespace MyFirstBot
{
public class DiscordBot
{
DiscordClient client;
CommandService commands;
TwitchClient TwitchClient;
TwitchAPIexample twitchLive = new TwitchAPIexample();
public DiscordBot()
{
if(twitchLive.Root == null || twitchLive.Root.Stream == null)
{
//stream is offline
}
}
}
}
So you are accessing the root object using the twitchLive.Root and trough the root you can access your stream twitchLive.Root.Stream

Unable To Parse JSON Response in C#

I am trying to parse a whois json response but when I try parse it I get null values.
string html;
string whoisUrl = "https://whois.apitruck.com/:google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(whoisUrl);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
html = reader.ReadToEnd();
}
}
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.created);
Object
class Class1
{
public string created { get; set; }
}
can anyone please point what I am doing wrong here ?
Your Class1 doesn't get the value since "created" is part of the "response" and not the root level of the JSON reponse.
You'll either need to use dynamic or create a hierarchy for the classes for a simple fix.
class Class1
{
public Response Response { get; set; }
}
class Response
{
public string created { get; set; }
}
Then you can use this:
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.Response.created);
UPDATE
Also, here's an example of how to use the dynamic:
var m = JsonConvert.DeserializeObject<dynamic>(html);
DateTime created = (DateTime)m.response.created;
There is nice app to convert json to .net class:
public class Registrar
{
public string id { get; set; }
public string name { get; set; }
public object email { get; set; }
public string url { get; set; }
}
public class Response
{
public string name { get; set; }
public string idnName { get; set; }
public List<string> status { get; set; }
public List<string> nameserver { get; set; }
public object ips { get; set; }
public string created { get; set; }
public string changed { get; set; }
public string expires { get; set; }
public bool registered { get; set; }
public bool dnssec { get; set; }
public string whoisserver { get; set; }
public List<object> contacts { get; set; }
public Registrar registrar { get; set; }
public List<string> rawdata { get; set; }
public object network { get; set; }
public object exception { get; set; }
public bool parsedContacts { get; set; }
}
public class RootObject
{
public int error { get; set; }
public Response response { get; set; }
}
...
RootObject result = JsonConvert.DeserializeObject<RootObject>(html);
var created = result.response.created;

Trying to receive JSON with JSON.net

I've started building an app to get tide info, weather info, mapping capabilities, etc from World Weather Online, but it can't get the JSON response.
I've installed JSON.net via NuGet, am running Windows 8.1. I've only been able to even view the data by pasting my JSON URL into an actual browser. Then using its output at json2sharp to create the bottom part of my code below.
Tried http://www.codeproject.com/Tips/397574/Use-Csharp-to-get-JSON-Data-from-the-Web-and-Map-i and How to get a json string from url?.
using System;
using System.Net;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GMap.NET.WindowsForms;
using GMap.NET;
using GMap.NET.MapProviders;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Web;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp;
using Newtonsoft.Json.Utilities;
namespace EOD_Assistant
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void myMap_Load(object sender, EventArgs e)
{
myMap.MapProvider = BingHybridMapProvider.Instance;
myMap.SetPositionByKeywords("Comox, Canada");
myMap.MinZoom = 1;
myMap.MaxZoom = 17;
myMap.Zoom = 10;
myMap.CanDragMap = true;
myMap.MapScaleInfoEnabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
string url = "http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&callback=rrr&key=1ccf49ff57a386e570286ae9294b9";
}
private void GetWeather()
{
}
private void weatherBtn_Click(object sender, EventArgs e)
{
}
public class WeatherDesc
{
public string value { get; set; }
}
public class WeatherIconUrl
{
public string value { get; set; }
}
public class CurrentCondition
{
public string cloudcover { get; set; }
public string FeelsLikeC { get; set; }
public string FeelsLikeF { get; set; }
public string humidity { get; set; }
public string observation_time { get; set; }
public string precipMM { get; set; }
public string pressure { get; set; }
public string temp_C { get; set; }
public string temp_F { get; set; }
public string visibility { get; set; }
public string weatherCode { get; set; }
public List<WeatherDesc> weatherDesc { get; set; }
public List<WeatherIconUrl> weatherIconUrl { get; set; }
public string winddir16Point { get; set; }
public string winddirDegree { get; set; }
public string windspeedKmph { get; set; }
public string windspeedMiles { get; set; }
}
public class Request
{
public string query { get; set; }
public string type { get; set; }
}
public class Astronomy
{
public string moonrise { get; set; }
public string moonset { get; set; }
public string sunrise { get; set; }
public string sunset { get; set; }
}
public class WeatherDesc2
{
public string value { get; set; }
}
public class WeatherIconUrl2
{
public string value { get; set; }
}
public class Hourly
{
public string chanceoffog { get; set; }
public string chanceoffrost { get; set; }
public string chanceofhightemp { get; set; }
public string chanceofovercast { get; set; }
public string chanceofrain { get; set; }
public string chanceofremdry { get; set; }
public string chanceofsnow { get; set; }
public string chanceofsunshine { get; set; }
public string chanceofthunder { get; set; }
public string chanceofwindy { get; set; }
public string cloudcover { get; set; }
public string DewPointC { get; set; }
public string DewPointF { get; set; }
public string FeelsLikeC { get; set; }
public string FeelsLikeF { get; set; }
public string HeatIndexC { get; set; }
public string HeatIndexF { get; set; }
public string humidity { get; set; }
public string precipMM { get; set; }
public string pressure { get; set; }
public string tempC { get; set; }
public string tempF { get; set; }
public string time { get; set; }
public string visibility { get; set; }
public string weatherCode { get; set; }
public List<WeatherDesc2> weatherDesc { get; set; }
public List<WeatherIconUrl2> weatherIconUrl { get; set; }
public string WindChillC { get; set; }
public string WindChillF { get; set; }
public string winddir16Point { get; set; }
public string winddirDegree { get; set; }
public string WindGustKmph { get; set; }
public string WindGustMiles { get; set; }
public string windspeedKmph { get; set; }
public string windspeedMiles { get; set; }
}
public class Weather
{
public List<Astronomy> astronomy { get; set; }
public string date { get; set; }
public List<Hourly> hourly { get; set; }
public string maxtempC { get; set; }
public string maxtempF { get; set; }
public string mintempC { get; set; }
public string mintempF { get; set; }
public string uvIndex { get; set; }
}
public class Data
{
public List<CurrentCondition> current_condition { get; set; }
public List<Request> request { get; set; }
public List<Weather> weather { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
public class PleaseWORK
{
private static T _download_serialized_json_data<T>(string url) where T : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}
}
}
}
Protocol is missing in the url
string url = "http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&callback=rrr&key=xxxxxxxxxxxxxxxxxxxxxxx";
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString(url); //THIS GIVES ME AN EXCEPTION ERROR....DUNNO WHY.
}
and the JSON string returnd by the api is not correct, it starts with "rrr" (at the time of writing of course)
string url = "http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&callback=rrr&key=1ccf49ff57a386e570286ae9294b9";
var jsonString = web.DownloadString(url).ToString();
var parseJsonString = jsonString.Split('(', ')')[1];
var obj = JsonConvert.DeserializeObject<RootObject>(parseJsonString);
This works, Check it...
You can get JSON string in this way
// httpWebRequest with API URL
HttpWebRequest request = (HttpWebRequest)WebRequest.Create
("http://YourURL.com");
//Method GET
request.Method = "GET";
//HttpWebResponse for result
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Mapping of status code
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == "")
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
//Get news data in json string
string data = readStream.ReadToEnd();
}
After that you can convert that string to DataSet also like this.
DataSet ds = new DataSet();
StringReader reader = new StringReader(data);
ds.ReadXml(reader);
The URL you're using is not correct.
To get valid json, you should use :
http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&key=xxxxxxxxxxxxxxxxxxxxx
The only difference is that i took out the &callback=rrr

Categories