✅ 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
leowest5mo ago
ok can u post a sample of that json?
leowest
leowest5mo ago
oof that's a big boy json
Yordle_Breeder
Yordle_Breeder5mo ago
yup.
leowest
leowest5mo ago
so for a start what I would do is copy the result
Angius
Angius5mo ago
$jsongen
MODiX
MODiX5mo 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
leowest5mo 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
Angius5mo ago
Or that, yeah
leowest
leowest5mo ago
then you said u want to filter for Today's weather?
Yordle_Breeder
Yordle_Breeder5mo ago
Oh I've done that The problem is the date format
Yordle_Breeder
Yordle_Breeder5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
I can already get the current weather from the Current nest
leowest
leowest5mo ago
You mean separate it by sun to sat? or
Yordle_Breeder
Yordle_Breeder5mo ago
Yah
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
That's what i thought as well
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
Okay. Thank you for your assistance
Angius
Angius5mo ago
DateOnly and DateTime both have a .DayOfWeek property
Yordle_Breeder
Yordle_Breeder5mo ago
Just the current week to display
leowest
leowest5mo ago
that should be more feasible
Yordle_Breeder
Yordle_Breeder5mo ago
So it's possible to make a functiont that can return just that day of the week?
Angius
Angius5mo ago
Yeah Looking at the JSON, all the dates should be parseable either into DateTime or DateOnly
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
Noice. In that way it would be easy to get the corellating temperature and icon
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
this => refers to the get function right?
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
mmm, kinda understand it
leowest
leowest5mo ago
FirstOrDefault loops thru the elements of today.Hour and if anything matches our predicate it returns that or null
Yordle_Breeder
Yordle_Breeder5mo ago
Okay, that's easy to understand now
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
Hmmm, I'll go throught it in a bit. Thanks a bunch man
leowest
leowest5mo ago
@ZZZZZZZZZZZZZZZZZZZZZZZZZ is there a native way to get these to a DateTime or somethin without a converter?
No description
leowest
leowest5mo 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
Angius5mo ago
time looks like it would work with a DateTime It's basically ISO8601
leowest
leowest5mo ago
that dash breaks it STJ doesn't like it
leowest
leowest5mo ago
No description
MODiX
MODiX5mo 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
Angius5mo ago
Huh
leowest
leowest5mo ago
{"The JSON value could not be converted to System.DateTime. Path: $.forecast.forecastday[0].hour[0].time | LineNumber: 0 | BytePositionInLine: 1433."}
Angius
Angius5mo ago
Then no, you'll need a custom converter
leowest
leowest5mo ago
weird
Angius
Angius5mo ago
For both, too
leowest
leowest5mo ago
yeah I mean u dont need for both since its the same value
Angius
Angius5mo ago
Since I don't think there's a way to convert a UNIX timestamp to a DateTime either, with STJ
leowest
leowest5mo ago
yeah I did a converter above which works
Angius
Angius5mo ago
Ah, well, then one or the other
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo 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>
Yordle_Breeder
Yordle_Breeder5mo ago
which ones did you change
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
also this. What deserialize method. I used readfromjsonasync to deserialize Oh ok
leowest
leowest5mo ago
that method is already deserializing
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo 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...");
}
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo ago
well I already showed up how to query there from the rsulting api
Yordle_Breeder
Yordle_Breeder5mo ago
From this right? There was bit of a data conversioon problem
Yordle_Breeder
Yordle_Breeder5mo ago
No description
leowest
leowest5mo 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}");
Yordle_Breeder
Yordle_Breeder5mo ago
what would be the value of json in this context is the value of json the unpacked data from the call?
leowest
leowest5mo ago
No description
leowest
leowest5mo ago
BlazeBin - wtmcpqrvxtum
A tool for sharing your source code with the world!
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo ago
huh did u link me the same thing
Yordle_Breeder
Yordle_Breeder5mo ago
no. there should be a second file
leowest
leowest5mo ago
am I blind I dont see it, did u save? oh now it shows up
Yordle_Breeder
Yordle_Breeder5mo ago
yah
Yordle_Breeder
Yordle_Breeder5mo ago
BlazeBin - yegiisxewmen
A tool for sharing your source code with the world!
leowest
leowest5mo 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; }
}
Yordle_Breeder
Yordle_Breeder5mo ago
nice nice, so you jsut use jsonpropertyname to remame a data entry you dont like
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
i cant seem to access the hour object but can access other properties directly like temp
leowest
leowest5mo ago
wdym?
Yordle_Breeder
Yordle_Breeder5mo ago
No description
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
I used the 7 day url
leowest
leowest5mo ago
why calling ToList again u just change the 7 to 1
Yordle_Breeder
Yordle_Breeder5mo ago
So i just call forcast ?
leowest
leowest5mo ago
no
Yordle_Breeder
Yordle_Breeder5mo ago
Its what you did
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
yah It seems your json on the paste.mode is a bit differenty
leowest
leowest5mo ago
yes it is, I did a bit modification to it in regards the data I dont need but your needs could be different
Yordle_Breeder
Yordle_Breeder5mo ago
No description
Yordle_Breeder
Yordle_Breeder5mo ago
it's not a list
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
that's what i'm calling?
leowest
leowest5mo ago
No description
Yordle_Breeder
Yordle_Breeder5mo ago
I guess i have to change one of the names
leowest
leowest5mo ago
yes you could just name it Day so it would look like forecast.Day.Hour :when:
Yordle_Breeder
Yordle_Breeder5mo ago
so something like this?
No description
leowest
leowest5mo ago
sure and remove the .ToList()
Yordle_Breeder
Yordle_Breeder5mo ago
also this was commented out. lol
leowest
leowest5mo ago
oh I see u have code above I didnt notice well can u show me the line above the one hour fails
Yordle_Breeder
Yordle_Breeder5mo ago
which line
leowest
leowest5mo ago
well I can't see what u had before that so I can't tell what today is there
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
so basically ROotOBject is the main nest?
leowest
leowest5mo ago
that's why u deserialize to it
leowest
leowest5mo ago
does VS not tell u what hte right hand is ?
No description
Yordle_Breeder
Yordle_Breeder5mo ago
No it doesnt.
leowest
leowest5mo ago
No description
leowest
leowest5mo ago
weird
Yordle_Breeder
Yordle_Breeder5mo 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?
Yordle_Breeder
Yordle_Breeder5mo ago
No description
leowest
leowest5mo ago
no that is right hour is a list
Yordle_Breeder
Yordle_Breeder5mo ago
but then i cant access anything after it
leowest
leowest5mo ago
look at what I do
Yordle_Breeder
Yordle_Breeder5mo ago
you did this "var time = today.Hour.FirstOrDefault(x => x.Time.Hour == DateTime.Now.Hour);" I cant do x.time.hour
leowest
leowest5mo ago
do this
leowest
leowest5mo ago
No description
leowest
leowest5mo ago
Display inline type hints
Yordle_Breeder
Yordle_Breeder5mo ago
now i see them
Yordle_Breeder
Yordle_Breeder5mo ago
No description
Yordle_Breeder
Yordle_Breeder5mo ago
i should have the right structure but i cant access anything after time
Yordle_Breeder
Yordle_Breeder5mo ago
But how do you access hour from time if they are in the same level
No description
leowest
leowest5mo ago
time.Hour
Yordle_Breeder
Yordle_Breeder5mo ago
No description
leowest
leowest5mo ago
you can look at the DateTime structure and its properties
Yordle_Breeder
Yordle_Breeder5mo ago
Literally cant do that
leowest
leowest5mo ago
why
Yordle_Breeder
Yordle_Breeder5mo ago
fml
leowest
leowest5mo ago
because your T is lower case duh
Yordle_Breeder
Yordle_Breeder5mo ago
nah my time was as a string
leowest
leowest5mo ago
No description
leowest
leowest5mo ago
but also your t is lower and in the property its upper at least what u showed above
Yordle_Breeder
Yordle_Breeder5mo ago
its not upper rn The problem was the datatype Im a moron
leowest
leowest5mo ago
dont forget to regenerate a new api key later since u posted it here ;P
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo ago
:PatrickChad:
Yordle_Breeder
Yordle_Breeder5mo ago
so for instance, if i want to bind the data for lets say tuesday, how do i do it
leowest
leowest5mo ago
what your vm looks like
Yordle_Breeder
Yordle_Breeder5mo ago
BlazeBin - dayfcwlqxqfs
A tool for sharing your source code with the world!
leowest
leowest5mo ago
and what is this? u want that to show only once? or multiple hours or what
leowest
leowest5mo ago
like I dont know exactly what u want to show in your view
Yordle_Breeder
Yordle_Breeder5mo ago
just the temp and icon for the days
leowest
leowest5mo ago
are u trying to show a card for each day of the week
Yordle_Breeder
Yordle_Breeder5mo ago
the hours dont count
leowest
leowest5mo ago
or for a single day
Yordle_Breeder
Yordle_Breeder5mo ago
for each day of the week
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo ago
well the error is clear and I said it my code was just a sample with no checks so forecast is null
Yordle_Breeder
Yordle_Breeder5mo ago
for forcast shouldnot be null
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
oh okay. I'll check it out odd weather.Forecast is null
leowest
leowest5mo ago
is json being filled with proper data?
Yordle_Breeder
Yordle_Breeder5mo ago
yes
leowest
leowest5mo ago
ok then something changed in Rootobject that is not mapping it or the json changed and broke that
Yordle_Breeder
Yordle_Breeder5mo ago
No description
leowest
leowest5mo ago
$paste
MODiX
MODiX5mo 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!
Yordle_Breeder
Yordle_Breeder5mo ago
I sshould paste the dataclass?
leowest
leowest5mo ago
the image above
Yordle_Breeder
Yordle_Breeder5mo ago
ok
leowest
leowest5mo ago
otherwise I can't properly view it reading minified json is ass 😉
Yordle_Breeder
Yordle_Breeder5mo ago
BlazeBin - itbwmesezoxe
A tool for sharing your source code with the world!
leowest
leowest5mo 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
MODiX5mo 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
leowest5mo ago
oh ops I automatically wrote the $ lol
Yordle_Breeder
Yordle_Breeder5mo ago
BlazeBin - rqswfexwvicp
A tool for sharing your source code with the world!
leowest
leowest5mo ago
thx is this a different end point? that json changed
Yordle_Breeder
Yordle_Breeder5mo ago
mmmmm I dont think so. It should still be the same one I didnt change the url from yesterday
leowest
leowest5mo ago
are u querying for a single day?
Yordle_Breeder
Yordle_Breeder5mo ago
fml it's different
leowest
leowest5mo ago
because that json clearly does not have the Forecast entry
Yordle_Breeder
Yordle_Breeder5mo ago
yah it doesnt
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
i'll try with the 7day call fml
leowest
leowest5mo ago
yeah I mean u need the whole week so u need 7 days and again add checks 😉
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo ago
u cannot breakpoint at today and try to see today's value u need to step in
Yordle_Breeder
Yordle_Breeder5mo 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
leowest5mo ago
huh u realize u can hover over it and see its values?
Yordle_Breeder
Yordle_Breeder5mo ago
yah.today is null, weather is not null
leowest
leowest5mo ago
No description
leowest
leowest5mo ago
and u said "its also not null" so why would it not be ok?
Yordle_Breeder
Yordle_Breeder5mo ago
Uhm i didnt know about the dropdown. Let me inspect
leowest
leowest5mo ago
its very debug is vs is very powerful 😉 u can even set locals and other things to analyze
Yordle_Breeder
Yordle_Breeder5mo ago
So i saw that what was null is day soo weather>forcast>day => null
leowest
leowest5mo ago
so we have to check day in the classes and if u addded the right name to the JsonPropertyName
leowest
leowest5mo ago
No description
Yordle_Breeder
Yordle_Breeder5mo ago
uhm so i tweaked a fewthings in the WeatherAPi but now another thing broke
No description
Yordle_Breeder
Yordle_Breeder5mo ago
Damn, bro makes it look easy 💀
leowest
leowest5mo ago
$paste your class again
MODiX
MODiX5mo 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
leowest5mo ago
u probably changed something wrong its easy once u understand it better until then its a lot of trial and error and debuging
Yordle_Breeder
Yordle_Breeder5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
BlazeBin - sbexsdoddrbx
A tool for sharing your source code with the world!
leowest
leowest5mo ago
yeah I changed mine a lot but waiting for u to have something working before i show u 😉
Yordle_Breeder
Yordle_Breeder5mo ago
lol, i guess it's part of the learning process. fine by me 🔥 Give me 30 mins. HEading back home
leowest
leowest5mo ago
rrrr let me rephrase
leowest
leowest5mo ago
ok so here
No description
leowest
leowest5mo ago
this works because the data is
leowest
leowest5mo ago
No description
leowest
leowest5mo 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
leowest5mo ago
No description
leowest
leowest5mo ago
No description
leowest
leowest5mo 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
Yordle_Breeder
Yordle_Breeder5mo ago
@leowest so i was able to properly parse the data 😄 Thanks to you $solved