C
C#3y ago
khamzat

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
khamzat
khamzatOP3y ago
khamzat
khamzatOP3y ago
this is just a json from roblox api
khamzat
khamzatOP3y ago
but what do i do to create a new class Rootobject data = new Rootobject ?
khamzat
khamzatOP3y ago
khamzat
khamzatOP3y ago
what do i do to set all the data i dont wanna hve to like manually set everything do u know? anyone?
Timtier
Timtier3y ago
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.
khamzat
khamzatOP3y ago
how can i use a deserialization? or do you maybe have example code?
Timtier
Timtier3y ago
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-to
How 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.
Timtier
Timtier3y ago
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.
khamzat
khamzatOP3y ago
hi i tried to deserialze the string that comes from the roblox api call
khamzat
khamzatOP3y ago
but i got an error
khamzat
khamzatOP3y ago
khamzat
khamzatOP3y ago
nevermind
khamzat
khamzatOP3y ago
khamzat
khamzatOP3y ago
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 thumbsupsmiley
Timtier
Timtier3y ago
Cool! catok 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-model
The 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#.
khamzat
khamzatOP3y ago
oh yeah my bot uses async patterns

Did you find this page helpful?