C
C#9mo ago
Kingdawanage

✅ Parsing JSON data to get unique data entries for each day of the week

I have a JSON from an api call and would like to have data for each day of the week seperated.
214 Replies
leowest
leowest9mo ago
ok can u post a sample of that json?
leowest
leowest9mo ago
oof that's a big boy json
Kingdawanage
KingdawanageOP9mo ago
yup.
leowest
leowest9mo ago
so for a start what I would do is copy the result
Angius
Angius9mo ago
$jsongen
MODiX
MODiX9mo ago
Use https://app.quicktype.io or https://json2csharp.com to generate classes from your JSON
Instantly parse JSON in any language | quicktype
Whether you're using C#, Swift, TypeScript, Go, C++ or other languages, quicktype generates models and helper code for quickly and safely reading JSON in your apps. Customize online with advanced options, or download a command-line tool.
Convert JSON to C# Classes Online - Json2CSharp Toolkit
Convert any JSON object to C# classes online. Json2CSharp is a free toolkit that will help you generate C# classes on the fly.
leowest
leowest9mo ago
then Edit > Paste Special > Json it will generate all the classes for you as a start it may not be perfect but will cut a lot of the work
Angius
Angius9mo ago
Or that, yeah
leowest
leowest9mo ago
then you said u want to filter for Today's weather?
Kingdawanage
KingdawanageOP9mo ago
Oh I've done that The problem is the date format
Kingdawanage
KingdawanageOP9mo ago
so like i need to have seperate entries for all days of the week but I'm not sure how to parse the data
No description
Kingdawanage
KingdawanageOP9mo ago
I can already get the current weather from the Current nest
leowest
leowest9mo ago
You mean separate it by sun to sat? or
Kingdawanage
KingdawanageOP9mo ago
Yah
leowest
leowest9mo ago
oh mmm I never done that I wonder if there is an out of the box way to do it or if u have to write your own logic
Kingdawanage
KingdawanageOP9mo ago
That's what i thought as well
leowest
leowest9mo ago
let me digest this massive json first so I can see how to get the days and I will get back to u u just want the current week or all weeks in a spectrum
Kingdawanage
KingdawanageOP9mo ago
Okay. Thank you for your assistance
Angius
Angius9mo ago
DateOnly and DateTime both have a .DayOfWeek property
Kingdawanage
KingdawanageOP9mo ago
Just the current week to display
leowest
leowest9mo ago
that should be more feasible
Kingdawanage
KingdawanageOP9mo ago
So it's possible to make a functiont that can return just that day of the week?
Angius
Angius9mo ago
Yeah Looking at the JSON, all the dates should be parseable either into DateTime or DateOnly
leowest
leowest9mo ago
so u just want teh day even easier I guess
var today = weather.forecast.forecastday.FirstOrDefault(x => x.date.Equals(DateTime.Now.ToString("yyyy-MM-dd"), StringComparison.InvariantCultureIgnoreCase));
var today = weather.forecast.forecastday.FirstOrDefault(x => x.date.Equals(DateTime.Now.ToString("yyyy-MM-dd"), StringComparison.InvariantCultureIgnoreCase));
Without changing anything from the paste json it would be I assume something like this if u change date to be DateOnly not sure if STJ supports it then its even easier to compare
Kingdawanage
KingdawanageOP9mo ago
Noice. In that way it would be easy to get the corellating temperature and icon
leowest
leowest9mo ago
yeah
var hour = today.Hour.FirstOrDefault(x => x.time.Hour == DateTime.Now.Hour);
hour.condition.icon
var hour = today.Hour.FirstOrDefault(x => x.time.Hour == DateTime.Now.Hour);
hour.condition.icon
so that would be the icon of that specific hour or if u prefer
Kingdawanage
KingdawanageOP9mo ago
this => refers to the get function right?
leowest
leowest9mo ago
imagine a foreach
Hour found = null;
foreach (Hour hour in today.Hour)
{
if (hour.time.Hour == DateTime.Now.Hour)
{
found = hour;
break;
}
}

Console.WriteLine(hour.condition.icon)
Hour found = null;
foreach (Hour hour in today.Hour)
{
if (hour.time.Hour == DateTime.Now.Hour)
{
found = hour;
break;
}
}

Console.WriteLine(hour.condition.icon)
its essentially that x is a predicate
Kingdawanage
KingdawanageOP9mo ago
mmm, kinda understand it
leowest
leowest9mo ago
FirstOrDefault loops thru the elements of today.Hour and if anything matches our predicate it returns that or null
Kingdawanage
KingdawanageOP9mo ago
Okay, that's easy to understand now
leowest
leowest9mo ago
so to make it easier, I changed on Forecastday
public DateOnly date { get; set; }
public DateOnly date { get; set; }
And changed on Hour
public DateTime time_epoch { get; set; }
public DateTime time_epoch { get; set; }
Then STJ didn't like the time_epoch so I made a custom parse on STJ
public class CustomJsonToDateTime : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(reader.GetInt32()).ToLocalTime();
return dateTime;
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
public class CustomJsonToDateTime : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(reader.GetInt32()).ToLocalTime();
return dateTime;
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
then u just add it to the deserialize method like so
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new CustomJsonToDateTime());
var weather = JsonSerializer.Deserialize<WeatherAPI.Rootobject>(json, options);
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new CustomJsonToDateTime());
var weather = JsonSerializer.Deserialize<WeatherAPI.Rootobject>(json, options);
so now u can compare date.Day against DateTime.Now.Day and time_epoch.Hour against DateTime.Now.Hour unhappily since it uses a custom time_epoch and date for the Hour u would need a parse anyway
Kingdawanage
KingdawanageOP9mo ago
Hmmm, I'll go throught it in a bit. Thanks a bunch man
leowest
leowest9mo ago
@ZZZZZZZZZZZZZZZZZZZZZZZZZ is there a native way to get these to a DateTime or somethin without a converter?
No description
leowest
leowest9mo ago
because they are both custom the date have a - separating it and the other a timestamp so I guess what I did above sounds about right?
Angius
Angius9mo ago
time looks like it would work with a DateTime It's basically ISO8601
leowest
leowest9mo ago
that dash breaks it STJ doesn't like it
leowest
leowest9mo ago
No description
MODiX
MODiX9mo ago
Angius
REPL Result: Failure
record Foo(DateTime Dt);
System.Text.Json.JsonSerializer.Deserialize<Foo>("""
{ "Dt": "2024-02-21 00:00" }
""")
record Foo(DateTime Dt);
System.Text.Json.JsonSerializer.Deserialize<Foo>("""
{ "Dt": "2024-02-21 00:00" }
""")
Exception: JsonException
- The JSON value could not be converted to Submission#0+Foo. Path: $.Dt | LineNumber: 0 | BytePositionInLine: 26.
- The JSON value could not be converted to Submission#0+Foo. Path: $.Dt | LineNumber: 0 | BytePositionInLine: 26.
Compile: 408.422ms | Execution: 66.308ms | React with ❌ to remove this embed.
Angius
Angius9mo ago
Huh
leowest
leowest9mo ago
{"The JSON value could not be converted to System.DateTime. Path: $.forecast.forecastday[0].hour[0].time | LineNumber: 0 | BytePositionInLine: 1433."}
Angius
Angius9mo ago
Then no, you'll need a custom converter
leowest
leowest9mo ago
weird
Angius
Angius9mo ago
For both, too
leowest
leowest9mo ago
yeah I mean u dont need for both since its the same value
Angius
Angius9mo ago
Since I don't think there's a way to convert a UNIX timestamp to a DateTime either, with STJ
leowest
leowest9mo ago
yeah I did a converter above which works
Angius
Angius9mo ago
Ah, well, then one or the other
Kingdawanage
KingdawanageOP9mo ago
Umm so i tried reading through what you did and my small brain couldnt fully grasp :sadge: So basically you made a class to parse custom JSOn
leowest
leowest9mo ago
I copy the resulting json u get from the api I then using visual studio go to Edit, Paste Special > Paste as JSON it generates all teh classes and properties to read the json not the best and sometimes u need to fix some stuff then I changed the type of 4 properties one to DateOnly one to DateTime and 2 to List<T>
Kingdawanage
KingdawanageOP9mo ago
which ones did you change
leowest
leowest9mo ago
and then I deserialize it with a custom method these 2 and mmm on Forecastday I changed public List<Hour> hour { get; set; } and on mmm Forecast public List<Forecastday> forecastday { get; set; } I could potentially change other properties to best fit the types I need, but those were the only ones that would make an impact in my needs at the moment I could also use [JsonPropertyName] to make the properties name follow a better c# convention like so
[JsonPropertyName("maxtemp_c")]
public float MaxTempCelcius { get; set; }
[JsonPropertyName("maxtemp_c")]
public float MaxTempCelcius { get; set; }
you also dont need all the json classes if u only need Hour class, then u can get away with removing a lot of the other json classes
Kingdawanage
KingdawanageOP9mo ago
I understand. I think i'll leave the other classes in case i want to build and this inthe future BUt the date_epoch What does it mean It's just a bunch of numbers
leowest
leowest9mo ago
same the time means except in seconds so I opted to convert that one instead I could have done the date doesn't matter
Kingdawanage
KingdawanageOP9mo ago
also this. What deserialize method. I used readfromjsonasync to deserialize Oh ok
leowest
leowest9mo ago
that method is already deserializing
Kingdawanage
KingdawanageOP9mo ago
I dont understand. I'm not sure how to implement the method you made. This is how i deserialized the json
public static async Task<DataClass.Rootobject> LoadData(string search)
{
string url = $"https://api.weatherapi.com/v1/current.json?key=382c30f637a04587915104833241502&q={Uri.EscapeDataString(search)}";

try
{
var response = await ApiHelper.ApiClient.GetAsync(url);
response.EnsureSuccessStatusCode();

var forecast = await response.Content.ReadFromJsonAsync<DataClass.Rootobject>();

return forecast;

}
catch (HttpRequestException ex)
{
MessageBox.Show($"HTTP request failed {ex.Message}");
throw;
}
catch (JsonException ex)
{
MessageBox.Show($"JSON decentralization failed {ex.Message}");
throw;
}
catch (Exception ex)
{
MessageBox.Show($"An error occured {ex.Message}");
throw;
}

}
public static async Task<DataClass.Rootobject> LoadData(string search)
{
string url = $"https://api.weatherapi.com/v1/current.json?key=382c30f637a04587915104833241502&q={Uri.EscapeDataString(search)}";

try
{
var response = await ApiHelper.ApiClient.GetAsync(url);
response.EnsureSuccessStatusCode();

var forecast = await response.Content.ReadFromJsonAsync<DataClass.Rootobject>();

return forecast;

}
catch (HttpRequestException ex)
{
MessageBox.Show($"HTTP request failed {ex.Message}");
throw;
}
catch (JsonException ex)
{
MessageBox.Show($"JSON decentralization failed {ex.Message}");
throw;
}
catch (Exception ex)
{
MessageBox.Show($"An error occured {ex.Message}");
throw;
}

}
Then i pass it to
public async Task UpdateCurrentData()
{
var dataInfo = await WeatherData.LoadData(SearchBoxText);
CurrentTemp = $"{dataInfo.current.temp_c}";
ConditionText = $"{dataInfo.current.condition.text}";
LocationName = $"{dataInfo.location.name}";

DateAndTime = $"{dataInfo.location.localtime}";
DateTime dateTime = DateTime.ParseExact(DateAndTime, "yyyy-MM-dd HH:mm", null);
string formatDateTime = dateTime.ToString("dddd, HH:mm");
DateAndTime = formatDateTime;

StatusImage = $"http:{dataInfo.current.condition.icon}";
}
public async Task UpdateCurrentData()
{
var dataInfo = await WeatherData.LoadData(SearchBoxText);
CurrentTemp = $"{dataInfo.current.temp_c}";
ConditionText = $"{dataInfo.current.condition.text}";
LocationName = $"{dataInfo.location.name}";

DateAndTime = $"{dataInfo.location.localtime}";
DateTime dateTime = DateTime.ParseExact(DateAndTime, "yyyy-MM-dd HH:mm", null);
string formatDateTime = dateTime.ToString("dddd, HH:mm");
DateAndTime = formatDateTime;

StatusImage = $"http:{dataInfo.current.condition.icon}";
}
and then proceed to bind the data to my UI elements
leowest
leowest9mo ago
if I wanted to convert the time instead of time_epoch it would be
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (DateTime.TryParse(reader.GetString(), out var result))
{
return result;
}
throw new InvalidDataException("Invalid DateTime format...");
}
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (DateTime.TryParse(reader.GetString(), out var result))
{
return result;
}
throw new InvalidDataException("Invalid DateTime format...");
}
Kingdawanage
KingdawanageOP9mo ago
mmm I just want the data to reflect the data of each day of the week regardless of when a search is made. I'm unsure how to apply this to do that The temperature and icon data
leowest
leowest9mo ago
well I already showed up how to query there from the rsulting api
Kingdawanage
KingdawanageOP9mo ago
From this right? There was bit of a data conversioon problem
Kingdawanage
KingdawanageOP9mo ago
No description
leowest
leowest9mo ago
yeah I didn't update the code to use the above changes
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new CustomJsonToDateTime());
var weather = JsonSerializer.Deserialize<WeatherAPI.Weather>(json, options);
var today = weather.forecast.forecastday.FirstOrDefault(x => x.date.Day == DateTime.Now.Day);
var time = today.hour.FirstOrDefault(x => x.time.Hour == DateTime.Now.Hour);
Console.WriteLine($"{time.temp_c} {time.condition.icon}");
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new CustomJsonToDateTime());
var weather = JsonSerializer.Deserialize<WeatherAPI.Weather>(json, options);
var today = weather.forecast.forecastday.FirstOrDefault(x => x.date.Day == DateTime.Now.Day);
var time = today.hour.FirstOrDefault(x => x.time.Hour == DateTime.Now.Hour);
Console.WriteLine($"{time.temp_c} {time.condition.icon}");
Kingdawanage
KingdawanageOP9mo ago
what would be the value of json in this context is the value of json the unpacked data from the call?
leowest
leowest9mo ago
No description
leowest
leowest9mo ago
BlazeBin - wtmcpqrvxtum
A tool for sharing your source code with the world!
leowest
leowest9mo ago
there is no checks for errors nulls or anything its just a PoC to show you 9 is celcius url is Icon I did not print anything else
Kingdawanage
KingdawanageOP9mo ago
Okay now i see. What confised me was the layout of my WeatherAPi json after i copy pasted. Mine was more like https://paste.mod.gg/swmemrjhpcms/1
BlazeBin - swmemrjhpcms
A tool for sharing your source code with the world!
leowest
leowest9mo ago
huh did u link me the same thing
Kingdawanage
KingdawanageOP9mo ago
no. there should be a second file
leowest
leowest9mo ago
am I blind I dont see it, did u save? oh now it shows up
Kingdawanage
KingdawanageOP9mo ago
yah
Kingdawanage
KingdawanageOP9mo ago
BlazeBin - yegiisxewmen
A tool for sharing your source code with the world!
leowest
leowest9mo ago
that is perfectly fine however I trimmed down things I didn't need for my example and used JsonPropertyName because I dont like db like names in c# like I said earlier the Paste Special is not the almight truth it can be prone to errors and bad things which u would have to fix an example is the 3 Condition clases that represent the exact same thing
public class Condition
{
public string text { get; set; }
public string icon { get; set; }
public float code { get; set; }
}

public class Condition1
{
public string text { get; set; }
public string icon { get; set; }
public int code { get; set; }
}

public class Condition2
{
public string text { get; set; }
public string icon { get; set; }
public int code { get; set; }
}
public class Condition
{
public string text { get; set; }
public string icon { get; set; }
public float code { get; set; }
}

public class Condition1
{
public string text { get; set; }
public string icon { get; set; }
public int code { get; set; }
}

public class Condition2
{
public string text { get; set; }
public string icon { get; set; }
public int code { get; set; }
}
so all these can be turned into a singel class
public class Condition
{
[JsonPropertyName("text")]
public string Text { get; set; }
[JsonPropertyName("icon")]
public string Icon { get; set; }
[JsonPropertyName("code")]
public int Code { get; set; }
}
public class Condition
{
[JsonPropertyName("text")]
public string Text { get; set; }
[JsonPropertyName("icon")]
public string Icon { get; set; }
[JsonPropertyName("code")]
public int Code { get; set; }
}
and here for example
public class Rootobject
{
public Location location { get; set; }
public Current current { get; set; }
public Forecast forecast { get; set; }
}
public class Rootobject
{
public Location location { get; set; }
public Current current { get; set; }
public Forecast forecast { get; set; }
}
Kingdawanage
KingdawanageOP9mo ago
nice nice, so you jsut use jsonpropertyname to remame a data entry you dont like
leowest
leowest9mo ago
I dont read Location or Current at all so I just removed them Deserialization only deserializes what u define so it dumps the information I dont want yes, so imagine the json name is "this_is_the_speed" I dont want a variable named that I would much rather call it Speed or TheSpeed for example the latter wouldn't happen thou 😛 it was just a bad example
Kingdawanage
KingdawanageOP9mo ago
Lol, at least i've learnt quite a bit this time. I will perform the implementation and show you
var time = today.Hour.FirstOrDefault(x => x.Time.Hour == DateTime.Now.Hour);
var time = today.Hour.FirstOrDefault(x => x.Time.Hour == DateTime.Now.Hour);
this line is to check the condition and temp per hour right?
leowest
leowest9mo ago
that gives me the Hour object for that hour yes and its then stored to time and I can access any of its properties
Kingdawanage
KingdawanageOP9mo ago
i cant seem to access the hour object but can access other properties directly like temp
leowest
leowest9mo ago
wdym?
Kingdawanage
KingdawanageOP9mo ago
No description
leowest
leowest9mo ago
keep in mind today access the list of ForecastDay with the day we want if instead of 7 in your API request u do 1 u only get Todays data from the API so u can skip that check altogether forecastday is already a list
Kingdawanage
KingdawanageOP9mo ago
I used the 7 day url
leowest
leowest9mo ago
why calling ToList again u just change the 7 to 1
Kingdawanage
KingdawanageOP9mo ago
So i just call forcast ?
leowest
leowest9mo ago
no
Kingdawanage
KingdawanageOP9mo ago
Its what you did
leowest
leowest9mo ago
u just remove ToList() forecastday is already a list calling tolist again does not benefit u assuming u did the 4 changes I did
Kingdawanage
KingdawanageOP9mo ago
yah It seems your json on the paste.mode is a bit differenty
leowest
leowest9mo ago
yes it is, I did a bit modification to it in regards the data I dont need but your needs could be different
Kingdawanage
KingdawanageOP9mo ago
No description
Kingdawanage
KingdawanageOP9mo ago
it's not a list
leowest
leowest9mo ago
you're looking in the wrong way List<Forecastday> ForecastDay is what defines it what you're calling line 66 on yours
public class Forecast
{
public List<Forecastday> forecastday { get; set; }
}
public class Forecast
{
public List<Forecastday> forecastday { get; set; }
}
its already a list and yet you're calling .ToList for no reason
Kingdawanage
KingdawanageOP9mo ago
that's what i'm calling?
leowest
leowest9mo ago
No description
Kingdawanage
KingdawanageOP9mo ago
I guess i have to change one of the names
leowest
leowest9mo ago
yes you could just name it Day so it would look like forecast.Day.Hour :when:
Kingdawanage
KingdawanageOP9mo ago
so something like this?
No description
leowest
leowest9mo ago
sure and remove the .ToList()
Kingdawanage
KingdawanageOP9mo ago
also this was commented out. lol
leowest
leowest9mo ago
oh I see u have code above I didnt notice well can u show me the line above the one hour fails
Kingdawanage
KingdawanageOP9mo ago
which line
leowest
leowest9mo ago
well I can't see what u had before that so I can't tell what today is there
Kingdawanage
KingdawanageOP9mo ago
it's changed but this is what's there now
public static async Task LoadWeeklyData(string search)
{
string url = $"https://api.weatherapi.com/v1/current.json?key=382c30f637a04587915104833241502&q={Uri.EscapeDataString(search)}";
var json = await new HttpClient().GetStringAsync(url);
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new CustomJsonToDateTime());

var weather = JsonSerializer.Deserialize<DataClass.Rootobject>(json, options);
var today = weather
}
public static async Task LoadWeeklyData(string search)
{
string url = $"https://api.weatherapi.com/v1/current.json?key=382c30f637a04587915104833241502&q={Uri.EscapeDataString(search)}";
var json = await new HttpClient().GetStringAsync(url);
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new CustomJsonToDateTime());

var weather = JsonSerializer.Deserialize<DataClass.Rootobject>(json, options);
var today = weather
}
stillf iguring out the class. a lot of classes are named forecast
leowest
leowest9mo ago
ok so weather.forecat.Day.FirstOrDefault ... your classes are all connected u just have to undestand tht so
public class Rootobject
{
public Location location { get; set; }
public Current current { get; set; }
public Forecast forecast { get; set; }
}
public class Rootobject
{
public Location location { get; set; }
public Current current { get; set; }
public Forecast forecast { get; set; }
}
this is what u are deserializing to so that is what weather is from there yo'ure calling forecast
public class Forecast
{
public List<Forecastday> forecastday { get; set; }
}
public class Forecast
{
public List<Forecastday> forecastday { get; set; }
}
etc etc
Kingdawanage
KingdawanageOP9mo ago
so basically ROotOBject is the main nest?
leowest
leowest9mo ago
that's why u deserialize to it
leowest
leowest9mo ago
does VS not tell u what hte right hand is ?
No description
Kingdawanage
KingdawanageOP9mo ago
No it doesnt.
leowest
leowest9mo ago
No description
leowest
leowest9mo ago
weird
Kingdawanage
KingdawanageOP9mo ago
it's making this pretty hard for me like too many identical names and all still cant access hour becasue something else is being called Hour is a list for you right?
Kingdawanage
KingdawanageOP9mo ago
No description
leowest
leowest9mo ago
no that is right hour is a list
Kingdawanage
KingdawanageOP9mo ago
but then i cant access anything after it
leowest
leowest9mo ago
look at what I do
Kingdawanage
KingdawanageOP9mo ago
you did this "var time = today.Hour.FirstOrDefault(x => x.Time.Hour == DateTime.Now.Hour);" I cant do x.time.hour
leowest
leowest9mo ago
do this
leowest
leowest9mo ago
No description
leowest
leowest9mo ago
Display inline type hints
Kingdawanage
KingdawanageOP9mo ago
now i see them
Kingdawanage
KingdawanageOP9mo ago
No description
Kingdawanage
KingdawanageOP9mo ago
i should have the right structure but i cant access anything after time
Kingdawanage
KingdawanageOP9mo ago
But how do you access hour from time if they are in the same level
No description
leowest
leowest9mo ago
time.Hour
Kingdawanage
KingdawanageOP9mo ago
No description
leowest
leowest9mo ago
you can look at the DateTime structure and its properties
Kingdawanage
KingdawanageOP9mo ago
Literally cant do that
leowest
leowest9mo ago
why
Kingdawanage
KingdawanageOP9mo ago
fml
leowest
leowest9mo ago
because your T is lower case duh
Kingdawanage
KingdawanageOP9mo ago
nah my time was as a string
leowest
leowest9mo ago
No description
leowest
leowest9mo ago
but also your t is lower and in the property its upper at least what u showed above
Kingdawanage
KingdawanageOP9mo ago
its not upper rn The problem was the datatype Im a moron
leowest
leowest9mo ago
dont forget to regenerate a new api key later since u posted it here ;P
Kingdawanage
KingdawanageOP9mo ago
sure. THanks a lot man. you have no idea how gratefull i am for your guidance I'll for sure accredit your name on my thesis if my work required .NET application
leowest
leowest9mo ago
:PatrickChad:
Kingdawanage
KingdawanageOP9mo ago
so for instance, if i want to bind the data for lets say tuesday, how do i do it
leowest
leowest9mo ago
what your vm looks like
Kingdawanage
KingdawanageOP9mo ago
BlazeBin - dayfcwlqxqfs
A tool for sharing your source code with the world!
leowest
leowest9mo ago
and what is this? u want that to show only once? or multiple hours or what
leowest
leowest9mo ago
like I dont know exactly what u want to show in your view
Kingdawanage
KingdawanageOP9mo ago
just the temp and icon for the days
leowest
leowest9mo ago
are u trying to show a card for each day of the week
Kingdawanage
KingdawanageOP9mo ago
the hours dont count
leowest
leowest9mo ago
or for a single day
Kingdawanage
KingdawanageOP9mo ago
for each day of the week
leowest
leowest9mo ago
ah ok so I would probably create a Model and fill a ObservableCollection with it so my Model would be just
public class Weather
{
public DateOnly Date {get;set;}
public float Temperature {get;set;}
public string IconUrl {get;set;}
}
public class Weather
{
public DateOnly Date {get;set;}
public float Temperature {get;set;}
public string IconUrl {get;set;}
}
so all that bloat json would return just that filling the ObservableCollection
Kingdawanage
KingdawanageOP9mo ago
So umm whats an observable collection Umm you know what. You've helped me a lot today. I'll call it a day and look into it tomorrow. I have an 8 am lecture tomorrow. THanks a bunch man. I mean it
leowest
leowest9mo ago
imagine a List<Weather> with INPC its pretty much a list that notifies the UI of changes to some extent but since u want the days and not the hours u might want to swap instead of Hour get the day since the day probably have an avg of the weather
Kingdawanage
KingdawanageOP9mo ago
@leowest I keep getting this error when i run this. I tried implementing the parser as a method to make my code more testable
No description
leowest
leowest9mo ago
well the error is clear and I said it my code was just a sample with no checks so forecast is null
Kingdawanage
KingdawanageOP9mo ago
for forcast shouldnot be null
leowest
leowest9mo ago
u might have changed that is causing the json to not deserialize to it? so u might add some null checks so u cna evaluate where its failing
Kingdawanage
KingdawanageOP9mo ago
public static async Task<DataClass.Hour>LoadWeeklyData(string search)
{
string url = $"https://api.weatherapi.com/v1/current.json?key=382c30f637a04587915104833241502&q={Uri.EscapeDataString(search)}";
var json = await new HttpClient().GetStringAsync(url);
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new CustomJsonToDateTime());

var weather = JsonSerializer.Deserialize<DataClass.Rootobject>(json, options);
var today = weather.Forecast.Forecastday.FirstOrDefault(x => x.Date.Day == DateTime.Now.Day);
var time = today.Hour.FirstOrDefault(x => x.Time.Hour == DateTime.Now.Hour);

return time;
}
public static async Task<DataClass.Hour>LoadWeeklyData(string search)
{
string url = $"https://api.weatherapi.com/v1/current.json?key=382c30f637a04587915104833241502&q={Uri.EscapeDataString(search)}";
var json = await new HttpClient().GetStringAsync(url);
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new CustomJsonToDateTime());

var weather = JsonSerializer.Deserialize<DataClass.Rootobject>(json, options);
var today = weather.Forecast.Forecastday.FirstOrDefault(x => x.Date.Day == DateTime.Now.Day);
var time = today.Hour.FirstOrDefault(x => x.Time.Hour == DateTime.Now.Hour);

return time;
}
the function. perhaps its because of the DataClass.Hour i put infront of the method constructor but i need to be able to return the time to store it in that model DataClass has the JSON format btw I also changed the relevant names using JsonPropertyName just to make extra sure
leowest
leowest9mo ago
the function. perhaps its because of the DataClass.Hour i put infront of the method constructor
sorry that made no sense can u explain at the very least the error has nothing to do with the method from what I can see today is null, add checks and find out where it is null is it because there is no Day == Day? is it because u changed the Model? is it because something else? u have to debug that
Kingdawanage
KingdawanageOP9mo ago
oh okay. I'll check it out odd weather.Forecast is null
leowest
leowest9mo ago
is json being filled with proper data?
Kingdawanage
KingdawanageOP9mo ago
yes
leowest
leowest9mo ago
ok then something changed in Rootobject that is not mapping it or the json changed and broke that
Kingdawanage
KingdawanageOP9mo ago
No description
leowest
leowest9mo ago
$paste
MODiX
MODiX9mo ago
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
Kingdawanage
KingdawanageOP9mo ago
I sshould paste the dataclass?
leowest
leowest9mo ago
the image above
Kingdawanage
KingdawanageOP9mo ago
ok
leowest
leowest9mo ago
otherwise I can't properly view it reading minified json is ass 😉
Kingdawanage
KingdawanageOP9mo ago
BlazeBin - itbwmesezoxe
A tool for sharing your source code with the world!
leowest
leowest9mo ago
can you start a new $paste so we dont get confused with yesterday stuff as I dont know how much of it changed
MODiX
MODiX9mo ago
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
leowest
leowest9mo ago
oh ops I automatically wrote the $ lol
Kingdawanage
KingdawanageOP9mo ago
BlazeBin - rqswfexwvicp
A tool for sharing your source code with the world!
leowest
leowest9mo ago
thx is this a different end point? that json changed
Kingdawanage
KingdawanageOP9mo ago
mmmmm I dont think so. It should still be the same one I didnt change the url from yesterday
leowest
leowest9mo ago
are u querying for a single day?
Kingdawanage
KingdawanageOP9mo ago
fml it's different
leowest
leowest9mo ago
because that json clearly does not have the Forecast entry
Kingdawanage
KingdawanageOP9mo ago
yah it doesnt
leowest
leowest9mo ago
so it only lists Today so note when u only query for 1 day it only gives u the Current info which is Todays forecast
Kingdawanage
KingdawanageOP9mo ago
i'll try with the 7day call fml
leowest
leowest9mo ago
yeah I mean u need the whole week so u need 7 days and again add checks 😉
Kingdawanage
KingdawanageOP9mo ago
so yah, my debugger shuts downafter it reachers the breakpoint var today line for some reason the debugger becomes unresponsive at the declaration of today line
leowest
leowest9mo ago
u cannot breakpoint at today and try to see today's value u need to step in
Kingdawanage
KingdawanageOP9mo ago
okay. i'll try again yah its null but weather is also not null. could only mean my DataClass class is not ok
leowest
leowest9mo ago
huh u realize u can hover over it and see its values?
Kingdawanage
KingdawanageOP9mo ago
yah.today is null, weather is not null
leowest
leowest9mo ago
No description
leowest
leowest9mo ago
and u said "its also not null" so why would it not be ok?
Kingdawanage
KingdawanageOP9mo ago
Uhm i didnt know about the dropdown. Let me inspect
leowest
leowest9mo ago
its very debug is vs is very powerful 😉 u can even set locals and other things to analyze
Kingdawanage
KingdawanageOP9mo ago
So i saw that what was null is day soo weather>forcast>day => null
leowest
leowest9mo ago
so we have to check day in the classes and if u addded the right name to the JsonPropertyName
leowest
leowest9mo ago
No description
Kingdawanage
KingdawanageOP9mo ago
uhm so i tweaked a fewthings in the WeatherAPi but now another thing broke
No description
Kingdawanage
KingdawanageOP9mo ago
Damn, bro makes it look easy 💀
leowest
leowest9mo ago
$paste your class again
MODiX
MODiX9mo ago
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
leowest
leowest9mo ago
u probably changed something wrong its easy once u understand it better until then its a lot of trial and error and debuging
Kingdawanage
KingdawanageOP9mo ago
yah. i think I'll down size my json classes get rid of the ones i dont need for it to be more coherent
Kingdawanage
KingdawanageOP9mo ago
BlazeBin - sbexsdoddrbx
A tool for sharing your source code with the world!
leowest
leowest9mo ago
yeah I changed mine a lot but waiting for u to have something working before i show u 😉
Kingdawanage
KingdawanageOP9mo ago
lol, i guess it's part of the learning process. fine by me 🔥 Give me 30 mins. HEading back home
leowest
leowest9mo ago
rrrr let me rephrase
leowest
leowest9mo ago
ok so here
No description
leowest
leowest9mo ago
this works because the data is
leowest
leowest9mo ago
No description
leowest
leowest9mo ago
DateOnly works because its just the date as u can see in the data date_epoch works with DateTime because we have a custom converter from int to DateTime however here
leowest
leowest9mo ago
No description
leowest
leowest9mo ago
No description
leowest
leowest9mo ago
you see its the other way around? so you have to mark time_epoch as DateTime and time u just leave as string otherwise u have to write another converter for some information u already own does that make sense? if u want u could even remove time from the model as u dont need it
Kingdawanage
KingdawanageOP9mo ago
@leowest so i was able to properly parse the data 😄 Thanks to you $solved
Want results from more Discord servers?
Add your server