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