UWP Get array from json Url - c#

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();

Related

How to deserialize an object and pass it to a response model

i have a json string that i deserialize as follows.
using (var streamReader = new StreamReader(httpResponsePayment.GetResponseStream()))
{
var data = streamReader.ReadToEnd();
result = JsonConvert.DeserializeObject<TestResponse>(data);
}
the data object looks as follows
"{\"responseCode\":2402,\"responseMessage\":\"hello\",\"amount\":0,\"acquirer\":{\"account\":{\"Number\":\"4587-54884-784848\"},\"Tag\":\"TF1234569775548494\"}}"
i pass this object to my TestResponse class
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
}
i can pass the above 3 objects correctly. I dont know how to pass the acquirer object to the TestResponse
acquirer = new
{
account= new
{
Number="4587-54884-784848"
},
Tag= "TF1234569775548494"
}
i tried doing something like this
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
List<Acquirers> acquirer =new List<Acquirers>();
}
public class Acquirers
{
public string Tag { get; set; }
}
also tried
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
public string Number {get;set;} //returns null
public string Tag {get;set;} // returns null
}
can someone please guide me
class Program
{
static void Main(string[] args)
{
var json = "{\"responseCode\":2402,\"responseMessage\":\"hello\",\"amount\":0,\"acquirer\":{\"account\":{\"Number\":\"4587-54884-784848\"},\"Tag\":\"TF1234569775548494\"}}";
var result = JsonConvert.DeserializeObject<Root>(json);
}
}
public class Account
{
public string Number { get; set; }
}
public class Acquirer
{
public Account account { get; set; }
public string Tag { get; set; }
}
public class Root
{
public int responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
public Acquirer acquirer { get; set; }
}
you can using this link = https://json2csharp.com/
for convert model

Unable to add an item to a database, ModelState.IsValid == false

I am working on an ASP.NET MVC application. Basically right now I'am trying to do the following: I created an API helper class that deserializes JSON data returned from Google Books API. In my Create.cshtml I only want to pass the ISBN of the book I am trying to add, however, as I discovered in debugger, ModelState.Is valid is false and therefore the new book does not get created. As far as I can see in the debugger, all the data gets pulled from the API correctly into the dictionary, however for some reason I can't store it my DB.
I know that there is probably a more elegant solution for this, but any kind of advice is more than welcome. Thank you for your time.
Here are the code files that might help:
APIHelper : deserializes JSON data and stores it in a Dictionary.
namespace APIHelper
{
public class IndustryIdentifier
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("identifier")]
public string Identifier { get; set; }
}
public class ReadingModes
{
[JsonProperty("text")]
public bool Text { get; set; }
[JsonProperty("image")]
public bool Image { get; set; }
}
public class ImageLinks
{
[JsonProperty("smallThumbnail")]
public string SmallThumbnail { get; set; }
[JsonProperty("thumbnail")]
public string Thumbnail { get; set; }
}
public class VolumeInfo
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("subtitle")]
public string Subtitle { get; set; }
[JsonProperty("authors")]
public IList<string> Authors { get; set; }
[JsonProperty("publisher")]
public string Publisher { get; set; }
[JsonProperty("publishedDate")]
public string PublishedDate { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("industryIdentifiers")]
public IList<IndustryIdentifier> IndustryIdentifiers { get; set; }
[JsonProperty("readingModes")]
public ReadingModes ReadingModes { get; set; }
[JsonProperty("pageCount")]
public int PageCount { get; set; }
[JsonProperty("printType")]
public string PrintType { get; set; }
[JsonProperty("categories")]
public IList<string> Categories { get; set; }
[JsonProperty("maturityRating")]
public string MaturityRating { get; set; }
[JsonProperty("allowAnonLogging")]
public bool AllowAnonLogging { get; set; }
[JsonProperty("contentVersion")]
public string ContentVersion { get; set; }
[JsonProperty("imageLinks")]
public ImageLinks ImageLinks { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("previewLink")]
public string PreviewLink { get; set; }
[JsonProperty("infoLink")]
public string InfoLink { get; set; }
[JsonProperty("canonicalVolumeLink")]
public string CanonicalVolumeLink { get; set; }
}
public class SaleInfo
{
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("saleability")]
public string Saleability { get; set; }
[JsonProperty("isEbook")]
public bool IsEbook { get; set; }
}
public class Epub
{
[JsonProperty("isAvailable")]
public bool IsAvailable { get; set; }
}
public class Pdf
{
[JsonProperty("isAvailable")]
public bool IsAvailable { get; set; }
}
public class AccessInfo
{
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("viewability")]
public string Viewability { get; set; }
[JsonProperty("embeddable")]
public bool Embeddable { get; set; }
[JsonProperty("publicDomain")]
public bool PublicDomain { get; set; }
[JsonProperty("textToSpeechPermission")]
public string TextToSpeechPermission { get; set; }
[JsonProperty("epub")]
public Epub Epub { get; set; }
[JsonProperty("pdf")]
public Pdf Pdf { get; set; }
[JsonProperty("webReaderLink")]
public string WebReaderLink { get; set; }
[JsonProperty("accessViewStatus")]
public string AccessViewStatus { get; set; }
[JsonProperty("quoteSharingAllowed")]
public bool QuoteSharingAllowed { get; set; }
}
public class SearchInfo
{
[JsonProperty("textSnippet")]
public string TextSnippet { get; set; }
}
public class Item
{
[JsonProperty("kind")]
public string Kind { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("etag")]
public string Etag { get; set; }
[JsonProperty("selfLink")]
public string SelfLink { get; set; }
[JsonProperty("volumeInfo")]
public VolumeInfo VolumeInfo { get; set; }
[JsonProperty("saleInfo")]
public SaleInfo SaleInfo { get; set; }
[JsonProperty("accessInfo")]
public AccessInfo AccessInfo { get; set; }
[JsonProperty("searchInfo")]
public SearchInfo SearchInfo { get; set; }
}
public class RootObject
{
[JsonProperty("kind")]
public string Kind { get; set; }
[JsonProperty("totalItems")]
public int TotalItems { get; set; }
[JsonProperty("items")]
public IList<Item> Items { get; set; }
}
public class APIHelper
{
public string Get(string uri)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
public Dictionary<string, string> DictionaryReturnData(string isbn)
{
string path = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;
string json = Get(path);
Dictionary<string, string> responses = new Dictionary<string, string>();
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
foreach (var obj in rootObject.Items )
{
responses.Add("Title", obj.VolumeInfo.Title);
responses.Add("Description", obj.VolumeInfo.Description);
responses.Add("Image", obj.VolumeInfo.ImageLinks.Thumbnail);
responses.Add("Authors", string.Join(",", obj.VolumeInfo.Authors)); //list of strings
responses.Add("Genre", string.Join(",", obj.VolumeInfo.Categories)); //list of strings
responses.Add("Isbn", isbn);
responses.Add("Publisher", obj.VolumeInfo.Publisher);
responses.Add("PublishedDate", obj.VolumeInfo.PublishedDate);
responses.Add("PageCount", obj.VolumeInfo.PageCount.ToString());
}
return responses;
}
}
}
My Book class:
namespace BookstoreWeb.Models
{
public class Book
{
public int Id { get; set; }
[Required]
public string Isbn { get; set; }
[Required]
public string Title { get; set; }
public string Author { get; set; }
public double Price { get; set; }
[Required]
public string Description { get; set; }
public string Publisher { get; set; }
public string PublishedDate { get; set; }
public string PageCount { get; set; }
public string Thumbnail { get; set; }
public string Genre { get; set; }
}
}
Create Action
[HttpPost]
public IActionResult Create(Book model)
{
APIHelper.APIHelper helper = new APIHelper.APIHelper();
var responses = helper.DictionaryReturnData(model.Isbn);
model.Author = responses["Authors"];
model.Genre = responses["Genre"];
model.Isbn = responses["Isbn"];
model.Price = 10.00;
model.Title = responses["Title"];
model.Description = responses["Description"];
model.Publisher = responses["Publisher"];
model.PublishedDate = responses["PublishedDate"];
model.PageCount = responses["PageCount"];
model.Thumbnail = responses["Image"];
if (ModelState.IsValid) //check for validation
{
var newBook = new Book
{
Author = model.Author,
Genre = model.Genre,
Isbn = model.Isbn,
Price = model.Price,
Title = model.Title,
Description = model.Description,
Publisher = model.Publisher,
PublishedDate = model.PublishedDate,
PageCount = model.PageCount,
Thumbnail = model.Thumbnail,
};
newBook = _bookstoreData.Add(newBook);
_bookstoreData.Commit();
return RedirectToAction("Details", new {id = newBook.Id});
}
Removing the annotations [Required] from Book class seems to have solved the issue.

C# JSON Get data from List<>

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.

Very slow downloading data to app

I writing uwp app.
I try to download json and display data.
I send to method lan and lon variables, put it and link and download data.
Location code:
public class LocationManager
{
public async static Task<Geoposition> GetPosition()
{
var accessStatus = await Geolocator.RequestAccessAsync();
if (accessStatus != GeolocationAccessStatus.Allowed) throw new Exception();
var geolocator = new Geolocator { DesiredAccuracyInMeters = 0 };
var position = await geolocator.GetGeopositionAsync();
return position;
}
}
Downloading JSON code:
private const string APPID = "f3c45b5a19426de9ea6ba7eb6c6969d7";
public async static Task<RootObject> GetWeather(double lat, double lon)
{
var http = new HttpClient();
var url = String.Format(
"http://api.openweathermap.org/data/2.5/weather?lat={0}&lon={1}&units=metric&APPID="+APPID, lat, lon);
var response = await http.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(RootObject));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (RootObject) serializer.ReadObject(ms);
return data;
}
}
[DataContract]
public class Coord
{
[DataMember]
public double lon { get; set; }
[DataMember]
public double lat { get; set; }
}
[DataContract]
public class Weather
{
[DataMember]
public int id { get; set; }
[DataMember]
public string main { get; set; }
[DataMember]
public string description { get; set; }
[DataMember]
public string icon { get; set; }
}
[DataContract]
public class Main
{
[DataMember]
public double temp { get; set; }
[DataMember]
public double pressure { get; set; }
[DataMember]
public double humidity { get; set; }
[DataMember]
public double temp_min { get; set; }
[DataMember]
public double temp_max { get; set; }
}
[DataContract]
public class Wind
{
[DataMember]
public double speed { get; set; }
[DataMember]
public double deg { get; set; }
}
/*
[DataContract]
public class Rain
{
[DataMember]
public double __invalid_name__1h { get; set; }
}
*/
[DataContract]
public class Clouds
{
[DataMember]
public int all { get; set; }
}
[DataContract]
public class Sys
{
[DataMember]
public int type { get; set; }
[DataMember]
public int id { get; set; }
[DataMember]
public double message { get; set; }
[DataMember]
public string country { get; set; }
[DataMember]
public int sunrise { get; set; }
[DataMember]
public int sunset { get; set; }
}
[DataContract]
public class RootObject
{
[DataMember]
public Coord coord { get; set; }
[DataMember]
public List<Weather> weather { get; set; }
[DataMember]
public string #base { get; set; }
[DataMember]
public Main main { get; set; }
[DataMember]
public Wind wind { get; set; }
/*
[DataMember]
public Rain rain { get; set; }
*/
[DataMember]
public Clouds clouds { get; set; }
[DataMember]
public int dt { get; set; }
[DataMember]
public Sys sys { get; set; }
[DataMember]
public int id { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public int cod { get; set; }
}
and there I show data like this:
public async void WeatherDisplay()
{
try
{
//var position = await LocationManager.GetPosition();
var geoLocator = new Geolocator();
geoLocator.DesiredAccuracy = PositionAccuracy.High;
Geoposition pos = await geoLocator.GetGeopositionAsync();
var lat = pos.Coordinate.Point.Position.Latitude;
var lon = pos.Coordinate.Point.Position.Longitude;
RootObject myWeather =
await OpenWeatherMapProxy.GetWeather(
lat,
lon);
Temperature.Text = ((int)myWeather.main.temp).ToString() + "°C";
// DescriptionTextBlock.Text = myWeather.weather[0].description;
City.Text = myWeather.name;
}
catch
{
}
}
My trouble in delays, I tap button and it show data in 30-40 seconds. With internet all okay. Why I have such big delays?

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;

Categories