how do i parse json into a class?
if i get json data from an api
i saw someone on youtube just paste it into vs2022 and it just creates a class with all the attributes
im wondering what do i do after this so i can create a class from getting the data
17 Replies
this is just a json from roblox api
but what do i do to create a new class
Rootobject data = new Rootobject ?
what do i do to set all the data
i dont wanna hve to like manually set everything
do u know? anyone?
At the moment when you fetch from the Roblox API, you usually have to do something along the lines of reading the content, like you did in the second screenshot.
At that point you use something called "Json deserialization" to turn the content, which often is a string or Stream, into a class of your choice.
how can i use a deserialization?
or do you maybe have example code?
Generally you use something like
System.Text.Json
or Newtonsoft.Json
to deserialize. Have a look here: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-toHow to serialize and deserialize JSON using C# - .NET
Learn how to use the System.Text.Json namespace to serialize to and deserialize from JSON in .NET. Includes sample code.
A warning though; some of the items in your Rootobject (which can also be renamed) currently have an
object
type, but if the value from the API is provided instead of null, this could cause some issues during deserialization.
You'd have to make some extra classes based on their documentation to catch that instead.hi i tried to deserialze the string that comes from the roblox api call
but i got an error
nevermind
i think i fixed it lets see
yesss
worked perfectly thank you so much
i used to manually read json data
by splitting with commas and stuff
very inefficient
i'll now optimize my discord
Cool!
Speaking of optimizations, you might want to look further into using
async
patterns in your bot later. You're already using the Async method but using .Result
is considered bad practice.
Making it asynchronous will mean that you'll be able to handle more requests at once. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/task-asynchronous-programming-modelThe Task Asynchronous Programming (TAP) model with async and await ...
Learn when and how to use Task-based async programming, a simplified approach to asynchronous programming in C#.
oh yeah my bot uses async patterns