Getting Exception when trying to retrieve data from "OpenWeatherMap.org" [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I am currently working on Weather API in which I am trying to take values from OpenWeatherMap.org. But When I click the button to retrieve the information from the website. It gives me the following Error.Here's the Screenshot of the exception,I am Getting
Also Here's the UI for Button I am clicking.
System.Exception was unhandled by user code
HResult=-2146233088
Message=Exception of type 'System.Exception' was thrown.
Source=UWPWeather
StackTrace:
at UWPWeather.LocationManager.<GetPosition>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at UWPWeather.MainPage.<Button_Click>d__1.MoveNext()
InnerException:
The OpenWeatherMapProxy.cs code:
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;
namespace WeatherAPI
{
public class OpenWeatherMapProxy
{
public async static Task<RootObject>GetWeather(double lat,double lon)
{
var http = new HttpClient();
var response = await http.GetAsync("http://api.openweathermap.org/data/2.5/weather? lat=35&lon=77.20081&appid=b1b15e88fa797225412429c1c50c122a");
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;
}
}
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 int pressure { get; set; }
[DataMember]
public int 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 int deg { 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 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; }
}
MainPage.xaml.cs code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace WeatherAPI
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
RootObject myWeather = await OpenWeatherMapProxy.GetWeather(20.0,30.0);
ResultTextBlock.Text = myWeather.name + " - " + ((int)myWeather.main.temp).ToString();
}
}
}

Here's the code running (it is running a console application):
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;
namespace ConsoleApplication1
{
public class OpenWeatherMapProxy
{
public async static Task<RootObject> GetWeather(double lat, double lon)
{
var http = new HttpClient();
var response = await http.GetAsync("http://api.openweathermap.org/data/2.5/weather?lat=35&lon=77.20081&appid=b1b15e88fa797225412429c1c50c122a");
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;
}
}
public class Coord
{
[DataMember]
public double lon { get; set; }
[DataMember]
public double lat { get; set; }
}
[DataContract]
public class Weather
{
[DataMember]
public double 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 Clouds
{
[DataMember]
public double all { get; set; }
}
[DataContract]
public class Sys
{
[DataMember]
public double type { get; set; }
[DataMember]
public double id { get; set; }
[DataMember]
public double message { get; set; }
[DataMember]
public string country { get; set; }
[DataMember]
public double sunrise { get; set; }
[DataMember]
public double 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 Clouds clouds { get; set; }
[DataMember]
public double dt { get; set; }
[DataMember]
public Sys sys { get; set; }
[DataMember]
public double id { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public double cod { get; set; }
}
class Program
{
static void Main(string[] args)
{
RootObject myWeather = Task.Run(() => OpenWeatherMapProxy.GetWeather(20.0, 30.0)).Result;
Console.WriteLine( myWeather.name + " - " + ((int)myWeather.main.temp).ToString());
}
}

((int)myWeather.main.temp).ToString()
I have to ask: Why to int and then back to string again??
Anyways, the answer to your problem:
You need to check that myWeather != null && myWeather.main != null && myWeather.main.temp != null
One of them is null, which is giving you the exception.

Related

How to deserialize a string containing multiple JSON [duplicate]

This question already has answers here:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value
(2 answers)
Closed 7 months ago.
From time to time, my system, through a Timer, executes a procedure that captures a list of events generated by the API, however, when trying to serialize, it returns the following error.
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: {. Path '[1].metadata', line 1, position 453.'
In this case, this is the string I get from the API.
[{"id":"6ed69e14-6610-4b57-a06f-328f38a9e2aa","code":"PLC","fullCode":"PLACED","orderId":"c6184662-2116-4a66-9f6b-4e6caca59e0d","merchantId":"355d10e6-8825-46e3-81dc-0961bf27a5dc","createdAt":"2022-07-14T12:45:34.142Z"},{"id":"e064302e-6a65-4821-ba4c-ea7021aaf8cc","code":"CAN","fullCode":"CANCELLED","orderId":"c6184662-2116-4a66-9f6b-4e6caca59e0d","merchantId":"355d10e6-8825-46e3-81dc-0961bf27a5dc","createdAt":"2022-07-14T12:53:34.674Z","metadata":{"CANCEL_STAGE":"[PRE_CONFIRMED]","ORIGIN":"IfoodGatewayAgent","CANCEL_CODE":"902","CANCELLATION_DISPUTE":{"IS_CONTESTABLE":"CANCELLATION_IS_NOT_CONTESTABLE","REASON":"NO_CREDIT_FOR_ORDER_LIABILITIES"},"CANCELLATION_OCCURRENCE":{"tags":["NO_CREDIT_FOR_ORDER_LIABILITIES"],"RESTAURANT":{"FINANCIAL_OCCURRENCE":"NA","PAYMENT_TYPE":"NA"},"CONSUMER":{"FINANCIAL_OCCURRENCE":"NA","PAYMENT_TYPE":"NA"},"LOGISTIC":{"FINANCIAL_OCCURRENCE":"NA","PAYMENT_TYPE":"NA"}},"TIMEOUT_EVENT":false,"CANCEL_ORIGIN":"RESTAURANT","CANCEL_REASON":"AUTOMATICO - NAO CONFIRMADO PELO RESTAURANTE","CANCEL_USER":"Order BackOffice Scheduler","CANCELLATION_REQUESTED_EVENT_ID":"17da3940-661e-4d9c-a15a-57f5d1b06474"}}]
This is the part that gives an error in the code:
var data = response.Content.ReadAsStringAsync();
var bodyResponse = JsonConvert.DeserializeObject<List<Classes.OrderStatus>>(await data);
Class OrderStatus:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace SAFI_Delivery.Classes
{
internal class OrderStatus
{
[JsonProperty("id")]
public string ID { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("fullCode")]
public string FullCode { get; set; }
[JsonProperty("orderId")]
public string OrderID { get; set; }
[JsonProperty("merchantId")]
public string MerchantID { get; set; }
[JsonProperty("createdAt")]
public string CreatedAt { get; set; }
[JsonProperty("metadata")]
public string Metadata { get; set; }
}
}
I would like to know how I make it consider that this is a list and not a string?
you have to fix classes and code
var json= await response.Content.ReadAsStringAsync();
var bodyResponse = JsonConvert.DeserializeObject<List<OrderStatus>>(json);
classes
public partial class OrderStatus
{
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("fullCode")]
public string FullCode { get; set; }
[JsonProperty("orderId")]
public Guid OrderId { get; set; }
[JsonProperty("merchantId")]
public Guid MerchantId { get; set; }
[JsonProperty("createdAt")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("metadata", NullValueHandling = NullValueHandling.Ignore)]
public Metadata Metadata { get; set; }
}
public partial class Metadata
{
[JsonProperty("CANCEL_STAGE")]
public string CancelStage { get; set; }
[JsonProperty("ORIGIN")]
public string Origin { get; set; }
[JsonProperty("CANCEL_CODE")]
public long CancelCode { get; set; }
[JsonProperty("CANCELLATION_DISPUTE")]
public CancellationDispute CancellationDispute { get; set; }
[JsonProperty("CANCELLATION_OCCURRENCE")]
public CancellationOccurrence CancellationOccurrence { get; set; }
[JsonProperty("TIMEOUT_EVENT")]
public bool TimeoutEvent { get; set; }
[JsonProperty("CANCEL_ORIGIN")]
public string CancelOrigin { get; set; }
[JsonProperty("CANCEL_REASON")]
public string CancelReason { get; set; }
[JsonProperty("CANCEL_USER")]
public string CancelUser { get; set; }
[JsonProperty("CANCELLATION_REQUESTED_EVENT_ID")]
public Guid CancellationRequestedEventId { get; set; }
}
public partial class CancellationDispute
{
[JsonProperty("IS_CONTESTABLE")]
public string IsContestable { get; set; }
[JsonProperty("REASON")]
public string Reason { get; set; }
}
public partial class CancellationOccurrence
{
[JsonProperty("tags")]
public List<string> Tags { get; set; }
[JsonProperty("RESTAURANT")]
public Consumer Restaurant { get; set; }
[JsonProperty("CONSUMER")]
public Consumer Consumer { get; set; }
[JsonProperty("LOGISTIC")]
public Consumer Logistic { get; set; }
}
public partial class Consumer
{
[JsonProperty("FINANCIAL_OCCURRENCE")]
public string FinancialOccurrence { get; set; }
[JsonProperty("PAYMENT_TYPE")]
public string PaymentType { get; set; }
}
Answered Question.
Thanks, Drew
I'm not too familiar with the JSON library you're using, but I suspect the issue is that, in your OrderStatus class, you have the Metadata property as a string type, but in your example JSON, the "metadata" key has an object value, not a string value.

Read xml node value

How to read all ExportHeaderType node value from below xml file.
<ArrayOfCEDataFileMappingSaveProp xmlns="http://schemas.datacontract.org/2004/07/Test.Models" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<CEDataFileMappingSaveProp>
<HeaderTypes>
<ExportHeaderType>
<AppType>LBX</AppType>
<DocType>Batch</DocType>
<HeaderType>Detail</HeaderType>
<CheckboxField>true</CheckboxField>
<DataFileMapPK>4</DataFileMapPK>
<IsHeaderRequired>false</IsHeaderRequired>
<IsHeaderTypeMandatory>true</IsHeaderTypeMandatory>
<Sequence>0</Sequence>
</ExportHeaderType>
</HeaderTypes>
<DocAppTypeId>LBX</DocAppTypeId>
<DocTypeId>Batch</DocTypeId>
<IsHeadingAvailable>false</IsHeadingAvailable>
</CEDataFileMappingSaveProp>
<CEDataFileMappingSaveProp>
<HeaderTypes>
<ExportHeaderType>
<AppType>LBX</AppType>
<DocType>Check</DocType>
<HeaderType>Detail</HeaderType>
<CheckboxField>true</CheckboxField>
<DataFileMapPK>4</DataFileMapPK>
<IsHeaderRequired>false</IsHeaderRequired>
<IsHeaderTypeMandatory>true</IsHeaderTypeMandatory>
<Sequence>0</Sequence>
</ExportHeaderType>
</HeaderTypes>
<DocAppTypeId>LBX</DocAppTypeId>
<DocTypeId>Check</DocTypeId>
<IsHeadingAvailable>false</IsHeadingAvailable>
</CEDataFileMappingSaveProp>
</ArrayOfCEDataFileMappingSaveProp>
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication11
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(ArrayOfCEDataFileMappingSaveProp));
ArrayOfCEDataFileMappingSaveProp array = (ArrayOfCEDataFileMappingSaveProp)serializer.Deserialize(reader);
}
}
[XmlRoot(Namespace = "http://schemas.datacontract.org/2004/07/Test.Models")]
public class ArrayOfCEDataFileMappingSaveProp
{
[XmlElement("CEDataFileMappingSaveProp")]
public List<CEDataFileMappingSaveProp> saveProp { get; set; }
}
public class CEDataFileMappingSaveProp
{
public string DocAppTypeId { get; set; }
public string DocTypeId { get; set; }
public Boolean IsHeadingAvailable { get; set; }
[XmlArray("HeaderTypes")]
[XmlArrayItem("ExportHeaderType")]
public List<HeaderTypes> headers { get; set; }
}
public class HeaderTypes
{
public string AppType { get; set; }
public string DocType { get; set; }
public string HeaderType { get; set; }
public Boolean CheckboxField { get; set; }
public int DataFileMapPK { get; set; }
public Boolean IsHeaderRequired { get; set; }
public Boolean IsHeaderTypeMandatory { get; set; }
public int Sequence { get; set; }
}
}
Try this
XmlSerializer serializer = new XmlSerializer(typeof(ArrayOfCEDataFileMappingSaveProp));
ArrayOfCEDataFileMappingSaveProp result;
using (StringReader reader = new StringReader(xml))
result = (ArrayOfCEDataFileMappingSaveProp)serializer.Deserialize(reader);
List<ExportHeaderType> exportHeaderTypes = result.CEDataFileMappingSaveProp.Select(c => c.HeaderTypes.ExportHeaderType).ToList();
result (in json format)
[{"AppType":"LBX","DocType":"Batch","HeaderType":"Detail","CheckboxField":"true","DataFileMapPK":"4","IsHeaderRequired":"false","IsHeaderTypeMandatory":"true","Sequence":"0"},
{"AppType":"LBX","DocType":"Check","HeaderType":"Detail","CheckboxField":"true","DataFileMapPK":"4","IsHeaderRequired":"false","IsHeaderTypeMandatory":"true","Sequence":"0"}]
classes
[XmlRoot(ElementName = "ArrayOfCEDataFileMappingSaveProp", Namespace = "http://schemas.datacontract.org/2004/07/Test.Models")]
public class ArrayOfCEDataFileMappingSaveProp
{
[XmlElement(ElementName = "CEDataFileMappingSaveProp", Namespace = "http://schemas.datacontract.org/2004/07/Test.Models")]
public List<CEDataFileMappingSaveProp> CEDataFileMappingSaveProp { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName = "i", Namespace = "http://www.w3.org/2000/xmlns/")]
public string I { get; set; }
}
[XmlRoot(ElementName="ExportHeaderType")]
public class ExportHeaderType {
[XmlElement(ElementName="AppType")]
public string AppType { get; set; }
[XmlElement(ElementName="DocType")]
public string DocType { get; set; }
[XmlElement(ElementName="HeaderType")]
public string HeaderType { get; set; }
[XmlElement(ElementName="CheckboxField")]
public bool CheckboxField { get; set; }
[XmlElement(ElementName="DataFileMapPK")]
public int DataFileMapPK { get; set; }
[XmlElement(ElementName="IsHeaderRequired")]
public bool IsHeaderRequired { get; set; }
[XmlElement(ElementName="IsHeaderTypeMandatory")]
public bool IsHeaderTypeMandatory { get; set; }
[XmlElement(ElementName="Sequence")]
public int Sequence { get; set; }
}
[XmlRoot(ElementName="HeaderTypes")]
public class HeaderTypes {
[XmlElement(ElementName="ExportHeaderType")]
public ExportHeaderType ExportHeaderType { get; set; }
}
[XmlRoot(ElementName="CEDataFileMappingSaveProp")]
public class CEDataFileMappingSaveProp {
[XmlElement(ElementName="HeaderTypes")]
public HeaderTypes HeaderTypes { get; set; }
[XmlElement(ElementName="DocAppTypeId")]
public string DocAppTypeId { get; set; }
[XmlElement(ElementName="DocTypeId")]
public string DocTypeId { get; set; }
[XmlElement(ElementName="IsHeadingAvailable")]
public bool IsHeadingAvailable { get; set; }
}

Parsing Open Weather Map API response fails [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I have this snippet of code:
public void getForcast()
{
string url = string.Format("https://samples.openweathermap.org/data/2.5/weather?q=London&appid=b6907d289e10d714a6e88b30761fae22");
using (WebClient web = new WebClient())
{
var json = web.DownloadString(url);
var obj = JsonConvert.DeserializeObject<WeatherData.WeatherForcast>(json);
WeatherData.WeatherForcast forcast = obj;
WeatherMark.Text = string.Format("{0}", forcast.list[1].weathers[0].description);
}
}
I want it to get description of it from forecast list.
But instead I'm getting this error
Object reference not set to an instance of an object
here's my whole list of classes:
class WeatherForcast
{
public List<list> list { get; set; }
}
public class weather
{
public string main { get; set; }
public string description { get; set; }
}
public class list
{
public List<weather> weathers { get; set; }
}
anyone knows why does it appear?
The JSON most likely does not match the provided class definition which results in a null object when parsed.
Calling the shown URL in a browser provides the following JSON response
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light
intensity
drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}
Which can be mapped to your shown code already provided with some modification.
public class WeatherForcast {
public List<weather> weather { get; set; }
}
public class weather {
public string main { get; set; }
public string description { get; set; }
}
There are online tools available where you can place the JSON and it will generate the mapped classes for the JSON.
You can get weather in Xml using &mode=xml and then use xml 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 = "https://samples.openweathermap.org/data/2.5/weather?q=London&mode=xml&appid=b6907d289e10d714a6e88b30761fae22";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(URL);
XmlSerializer serializer = new XmlSerializer(typeof(Weather));
Weather weather = (Weather)serializer.Deserialize(reader);
}
}
[XmlRoot("current")]
public class Weather
{
public City city { get; set; }
public Temperature temperature { get; set; }
public Humidity humidity { get; set; }
public Pressure pressure { get; set; }
public Wind wind { get; set; }
}
public class City
{
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public string id { get; set; }
public Coord coord { get; set; }
public string country { get; set; }
public Sun sun { get; set; }
}
public class Sun
{
[XmlAttribute()]
public DateTime rise { get; set; }
[XmlAttribute()]
public DateTime set { get; set; }
}
public class Coord
{
[XmlAttribute()]
public decimal lon { get; set; }
[XmlAttribute()]
public decimal lat { get; set; }
}
public class Temperature
{
[XmlAttribute()]
public decimal value { get; set; }
[XmlAttribute()]
public decimal min { get; set; }
[XmlAttribute()]
public decimal max { get; set; }
}
public class Humidity
{
[XmlAttribute()]
public decimal value { get; set; }
}
public class Pressure
{
[XmlAttribute()]
public decimal value { get; set; }
}
public class Wind
{
public Speed speed { get; set; }
public Direction direction { get; set; }
}
public class Speed
{
[XmlAttribute()]
public decimal value { get; set; }
[XmlAttribute()]
public string name { get; set; }
}
public class Direction
{
[XmlAttribute()]
public decimal value { get; set; }
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public string code { get; set; }
}
}

Returning multiple joined/navigation objects

I recently inherited an ASP.NET Entity Framework API project.
I managed to do basic changes that were needed, but I'm getting a little lost with advanced SQL requests (I'm more a Symfony dev, I don't know Entity Framework).
I need to add a GET method to my API that will take a service (prestation) and will return a list of all the partners (Partenaires) who has a service (Prestation) with the same name as the GET parameter.
Here's the actual prototype of the method:
// GET: api/Partenaires_prestations
[Authorize]
public List<PartenaireMapItem> GetPartenairesWithPrestations(string prestation = "")
{
if (string.IsNullOrWhiteSpace(prestation))
{
prestation = "";
}
return db.Partenaires
.Join() // Here I don't know what to do
}
I have 3 tables that I have to use:
Prestation, Partenaires, PartenairesPrestation
Here are the 3 tables classes:
namespace Uphair.EfModel
{
using System;
using System.Collections.Generic;
public partial class Partenaire
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Partenaire()
{
this.PartenairePrestations = new HashSet<PartenairePrestation>(); // I took out the useless parts
}
public int IdPartenaire { get; set; }
[...] // I took out properties that are not needed
public virtual ICollection<PartenairePrestation> PartenairePrestations { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
namespace Uphair.EfModel
{
using System;
using System.Collections.Generic;
public partial class PartenairePrestation
{
public int IdPartenaire { get; set; }
public int IdPrestation { get; set; }
public double Prix { get; set; }
public int Duree { get; set; }
public Nullable<System.DateTime> DateAjout { get; set; }
public virtual Partenaire Partenaire { get; set; }
public virtual Prestation Prestation { get; set; }
}
}
namespace Uphair.EfModel
{
using System;
using System.Collections.Generic;
public partial class Prestation
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Prestation()
{
this.PartenairePrestations = new HashSet<PartenairePrestation>();
this.PrixDureeOptions = new HashSet<PrixDureeOption>();
this.LigneReservations = new HashSet<LigneReservation>();
}
public int IdPrestation { get; set; }
public string NomPrestation { get; set; }
public int Categorie { get; set; }
public Nullable<int> CoifEsthe { get; set; }
public Nullable<int> IdPrestationCategorie { get; set; }
public virtual ICollection<PartenairePrestation> PartenairePrestations { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
The last one makes the link between Partenaires and Prestation via IdPartenaire and IdPrestation columns.
Here's a screenshot of my model structure:
https://imageshack.com/a/img922/9111/4twiC8.png (imgur is not responding sorry)
Here's the PartenaireMapItem model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Uphair.EfModel;
namespace Uphair.Api.Models.Partenaire
{
public class PartenaireMapItem
{
public int IdPartenaire { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string NomComplet { get; set; }
public double? Lat { get; set; }
public double? Lng { get; set; }
public PartenaireType Type { get; set; }
public int DureeMin { get; set; }
public string ImageUrl { get; set; }
public int SeDeplace { get; set; }
public bool ADomicile { get; set; }
public double NoteGlobale { get; set; }
public List<String> Prestations { get; set; }
}
}
I need to use join to get a list of partners (Partenaires) that have the service (Prestation) with the service name provided in the GET parameter, but I don't know how to do it.
Any help would be welcome, thanks to anyone who will take the time to read/answer me.

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