JSON IN C# - Downloading Data and Making Objects From It

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up youtube this is dennis panuta for tutorials.eu in this video you are going to learn about jason and not this jason but that jason and jason is going to be super important when it comes to getting data from the internet because it's just a format that allows you to read it as a human being but at the same time it's very readable for a computer so let's have a look at json serialization deserialization and all of the good stuff and by the way if you enjoyed this video please hit that like button and also the subscribe button it really helps us out thanks a lot now let's get started all right so let's get started with a small presentation before we get into a practical example json stands for javascript object notation which is an open standard file format and a data interchange format that uses human readable text to store and transmit data objects the power of json is that we can convert strings into objects in any programming language and vice versa so convert objects to strings which we can then send over the network or store locally to retrieve them later json object has the following format our curly brackets that will contain the data of our json then we write down the key or the name of the variable in this case its name and then we add the colon as well as the value that we want to store inside of that key so in this case it's the name and it's going to be civ so we have the name of civ and if we want to add more data we then separate it by a comma and add the additional data in this case the age which is set to 12. so in c-sharp this object will then translate into two properties a name and an age so this would be an example here then we convert this json object or string into an object that we can deal with as with any c-sharp objects but how do we convert json to c-sharp objects and vice versa well for that we use the concept of serialization and deserialization let's assume that we load our json data or received it from a server and we managed to store it as a string note that the add sign before the beginning of our string just means that our string is taken verbatim or literally which means we will not need to add a backslash for example for backslash n or backslashes in general when we want to create a blind break this is pretty useful when it comes to json strings so instead for example of using a backslash where we would have to first use a escape character backslash in order to then use the backslash we would just use one backslash okay so that's what this add verbatim does so to convert a json string to a c sharp object we can then use a class called json convert and we use a static method called deserialize object and we give it the type of class we want to convert the json to which in this case is going to be dog and we pass the json string that we have created this will give us back a dog object which has the same values as the json string by matching the keys so the name and h this will give us back a player object which has the same values as the json string by matching the keys in this case name and h with the property names we have in our class the d serialize object method uses the concept of deserialization which is a concept in c sharp that will read text or a string and convert it into a c sharp object the opposite of deserialization is serialization in which c-sharp class objects are written or serialized to text or strings and we can use it like this so we pass the dog object into a static method of the json convert class called serialize object and it will return the object in json format as a string so we can then send the string to a server or store it in a file to load it later so what about collections in json well back to our dog class let's say every dog will have a bunch of toys since our class must match the json we will be serializing and deserializing so we can add the toys to our class as an array or a list of string and the json representation can look something like this so this json representation of our dog class from before and the ray of dog toys will be in this format as well so here toys plush bear ball and we start like any json property by writing the name of the property which is toys and then the value part we will have the content of the array inside of the squared brackets here and then the serialization and the serialization will remain the same so when you are dealing with json you are probably getting it from an api the data you are fetching could be representing a table in a database which means you won't be receiving a single json object but a collection of json objects a collection of json objects that can be parsed into an array of dogs will look something like this note how all of your json objects are separated by a comma and then they are surrounded by square brackets so now to convert this array of json objects we can just parse it into an array of docs alright now that you are a specialist in json let's go ahead and use it in visual studio quick pause in this video you'll learn something about c sharp and if you want to learn everything there is to know that you need for the fundamentals and to become a real c-sharp developer then definitely check out my c-sharp master class in which you're going to learn all of the things you need to know about c-sharp so you're going to learn how to do the basics how to use object oriented programming how to use wpf in order to create your own user interfaces how to use databases how to use link how to create your own games using unity and a lot more so if you want to become a real c sharp developer definitely check out the link in the description below therefore let's go ahead and create a new console application and then go over to tools and here new get package manager and then manage nuget packages for solution so here we want to install the newton soft solution and i'm going to browse and not look in my installed versions so here you see newtonsoft.json that's the one that i want to make sure that i have so here let's apply this to my project and install the latest stable version and then press ok ok now json will be installed for our project and we can use it all right now i don't want to just teach you how to use json and that's it i want to give you the real view so we will fetch a json string from an online api and then parse it into c-sharp objects and work with them and for that we will use a fake json server and we will be sending an actual get request to get this fake server information so this website can help you with that so my json server and it's a website that can build a fake json server that works like a web service that can accept rest api calls like get put etc so rest are the api calls that you are going to require for any kind of server side requests the way it works is that you will create a public repository on github then add a json file to it that contains the json data you want to simulate then you can access the fake json server using my json server with your github username and the repo name in the url but since this is outside the scope of this lecture we'll use a fake json server they have as a demo so just click on try free server so just click on try a server which you can find further down here over there all right and then just go on posts and that's pretty much it so you have a list of posts that have an id as well as a title so this means you have a collection of post objects where we have those two properties so let's go ahead and copy this url because we're going to use it in our project now let's go back to visual studio and create a new url so i'm going to create a string url which will be in fact this url that we just copied so i'm going to store it in my url variable so that i can use it later on okay so this would then of course be replaced with the url where you get the data from so now since we are the client who's going to send the get requests we need to define a new http client all right so let's go ahead and also create an http client object here all right now you see that http client doesn't exist in this context so we need to add this namespace and while we're adding namespaces let's also make sure that we are using the newtonsoft json namespace because we're going to use its methods later on so now we need to try and send a get request since there are countless reasons why this process might fail however we need to use a try and catch block for this so let's go ahead and use and try and catch here so just use try press tab twice and it will generate the code for you so how does such a request look like well you're using a new variable i'm going to call this one response message so i'm setting up the variable with the await keyword because this is going to run asynchronously so let's go ahead and use the httpclient.getasync method here passing our url the one that we created earlier like so and here i want to use the http client that we had set up ourselves this one here now as you can see from the above code we sent our get request using get async but we added a weight keyword beforehand so this keyword here this is because we need to await the get async method to finish but at the same time we don't want to freeze our application but we can't wait inside a non-async method and our main method here is not an async method so we need to make sure that this method is going to actually going to be an async method so let's do that let's make it async but that by itself is not enough because we also need now to return a task so now our main method will return a task asynchronously so for now let's go ahead and write a message in case we get an error here as well as make sure that we are actually returning something all right now because we are using static or our static main method we need to make sure that these variables either would be static or we are just going to make them local so that we're going to use them in the same scope as the main method okay so now we don't get this arrow here anymore and let's also make sure that this exception is going to have a name called e so we actually get an object of the exception that appeared also because we are using a task here the task class we need to make sure to also add system threading tasks up here all right now we're good to go so you see in order to get data from a url you need to understand async and the weight and we have a video for this where i go into depth how async and await works and how you can set it up for yourself in the future as well so check that one out you can find the link in the description so now let's go ahead and use this response message and actually convert it into something that we can use so let's make it a json response let's create content out of it so we are awaiting to load the entire page it will be stored in the response message which is not going to be the actual data but now we can get the data from the content of that response message using the await method as well so here let's read the string from the response content using await http responsemessage.content and read as a string asynchronously because this is using an await method and then stuff suddenly happens asynchronously so we need to make sure that this doesn't block our main thread and our program will still be able to work even though we're doing such a heavy load kind of work all right and now let's actually print that response onto our console so i'm just going to use a console.writeline here so now let's run the application and check it out so you see we get the collection of posts so that by itself has nothing to do with json specifically this is so far just to get the data from an api and use it in json so now let's actually look at jason all right so now you might be guessing oh nexus dennis is going to create a c-sharp class with two properties called post and the properties are going to be id as well as title well yeah in my tutorials i always aim to teach you new stuff that can make your a better developer so we're not going to do that manually also it's 2021 in the time of this recording so let's use a robot that can create this for us so let me show you a few tools that will come in handy if you are working with json in general the first one is going to be json2 c-sharp and from its name it's a tool that takes a json string and creates a c-sharp class that matches the json we gave it okay so here we can just go ahead and use this code that we have here put it in there and make c-sharp code from it so here json into c-sharp press convert and then it converted it and created the class for us so this one is pretty simple right nothing too fancy pretty simple code we could have done it very quickly as well we don't need to use this here for that but now let's say we have a more complex json format like this one so this is the data that you're getting so an object has a bunch of properties so result for example is also json object which has an email which has a bunch of other stuff so it's a lot more complicated to build this manually so let's convert it for ourselves and you see now it created everything for us so let me scroll in out a little bit so you see we have all of these classes that we're going to require for this particular case so in our particular case it was super easy but if it's a little more complicated then using json2 c sharp is really going to help you out so let me go back to my simple example and use that code in my project as well all right then by the way you can also change the settings so here you can use pascal case as well as add to json property attributes and this will then create the code like this for you okay so i'm going to rename it called post so you see here it added the json property attribute called id for it so now let's copy that to the clipboard and go back to visual studio where we're going to now create a new class so open the solution explorer if you want to by going to view solution explorer and then create a new class so add or you can use ctrl k and see the shortcut which will do the same thing i'm going to call this one post.cs and now let's paste the code in here so here this would be of course post so now for json property to work you need to add using newton soft json at the top here so this name space at the top will then allow you to use this json property so now you might be wondering what is this json property for example with the id there well this is an attribute that tells the json package we are using the name is id and we want it to be matched to the json property id with our posts class property id if we don't add this attribute then instead we need to write our properties in the same way that they are defined in our json response so here this id uses a capital i but here it's used with a low capsize so if you look at the data we're getting here we're getting a lower eye but we are actually having the property names using a capital i so that's what this json property does for us so it just says okay whatever we're getting as id should be using this property here this is useful if we want to use the property name user id instead of id in our code for example but still parse it correctly so we could change that in our code even though it's really recommended to use it pretty similarly maybe changing the capitalization but that's it so now let's parse and deserialize the json response into an array of type posts since we remember we are receiving a collection of posts not just one post so let's go back to our program cs here and let's start deserializing so i'm going to show you how that's done by using the json convert class which comes from newtonsoft so the nuget package which we added and then you can use the serialize object method here so what we're saying is we are getting the json response which is this one here which was the string that we earlier brought onto the console so this one here and we say that this is going to be an array of posts so these utilize that into my posts so this will be containing an array of posts now let's go ahead and let's iterate through each of the objects that we have in there so i'm going to use it for each loop here where i go through every single post in my posts and i'm going to use the id as well as the title to display them onto the console okay so let's run this code and see what's going to happen and we can see the id is one and the name is post one the id is two and the host name or title as pos2 and so forth okay so we're basically now getting the data and we're bringing it into a format that we can now use so now you could go ahead and just display one information about it for example just the title or whatever information you want to have so in this case it's a quite simple example right but it could be a lot more complex as we saw earlier with all of the different classes that we had here for example right with all of the different properties and so forth so now there's just one last important step that we need to do and that is to make sure that we are actually disposing of our http client okay because we're opening it and we need to make sure that once we're done with the try block we also have a finally block here and we dispose of the http client here so let's go ahead and do that otherwise it would stay open and that's never a good idea okay so that's pretty much our code now let's run this and well nothing has changed but our program works flawlessly now you have seen how to use json how to get the json data and then break it down into individual parts that you can use in c sharp okay now one last thing really so there is something called codebeautify.org which is a great website which allows you to beautify your code so i'm going to use this code that we had earlier which was pretty complex right this is json code and now i can beautify it by just pressing this beautify button and it will bring it into a format that is more readable in many cases so you see here there are a bunch of empty spaces and so forth and you can basically change it you can beautify it you can have a tree viewer which is pretty cool so we have an object with three properties json rpc an id as well as a result and this result has 10 properties so it has an email an id and so forth and then we have a portfolio which has two properties and eth and btc so ethereum and bitcoin so this ethereum has eight properties with all of this data okay so that is something that code beautify can do for you and the whole thing com becomes a lot easier to handle because what you see here is really a bunch i'd say and using code beautify is really helpful here alright so we learned about json and how to use a fake json server to fetch json data online as well as how to parse json strings into c sharp objects or pocos which are plain old clr objects now there is still a lot of stuff that you might want to learn about for example creating a json server on your local host for more complex rest operations or you might want me to dive deeper into newton soft into this json package or maybe you want to learn more about async and weight in that case you know what to do just leave a comment and let us know about what you are still interested in and also don't forget to hit that like button if you haven't done so already and smash that subscribe button in order to not miss out on any great videos that we're publishing in the next couple of months all right and also check out the c sharp master class you can find the link in the description below and now thanks a lot for watching the video see you in the next one
Info
Channel: tutorialsEU
Views: 1,602
Rating: undefined out of 5
Keywords: Tutorials, Tutorial, Programming, Course, Learn, Step by step, guide, development, programmer, video course, video tutorial, learn how to, how to, “c# create json string dynamically, c# json object example, create a json object in c#, c# create json object without class, c# create json string manually, how to create nested json object in c#, create json file c# newtonsoft, create json object c# newtonsoft, JSON C# tutorial, learn JSON C#, about json, what is json in tamil
Id: N6JBjzPssQI
Channel Id: undefined
Length: 24min 9sec (1449 seconds)
Published: Fri Jul 16 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.