What is JSON - JSON Parsing in Swift

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Hey CodeCrew, we talked about APIs last week so it only makes sense to talk about JSON parsing this week :)

👍︎︎ 1 👤︎︎ u/CodeWithChris 📅︎︎ Feb 07 2020 🗫︎ replies
Captions
hey code crew last week we talked about what api's were if you missed that video check it out right over there this week let's talk about what JSON is and why it's so important especially for mobile app development by the end of this video you'll understand how to read the JSON as well as how to parse JSON in Swift okay so what is JSON JSON is a standard data format and it's often used for the response data that you get back from an API for example if you wanted to pull some information from Facebook you'd make a request to the Facebook API endpoint for that information and then the API would return the information to you in the JSON data format that's why it's really important to understand how to read the JSON data format and how to parse it which is just the technical term for processing the JSON data into a usable format for your app in this video I'll break down the JSON formatting so that you can understand it and then I'll take you through a practical example of parsing JSON in Swift there are only three things you need to know in order to understand the JSON data format the first thing is what a key value pair is the value part of the pair is the actual data and the key part is usually a piece of text that describes what the data represents together the key and the value represents one piece of data to group together relevant key value pairs use a comma to separate each key value pair and then put a pair of curly brackets around the entire group when you organize a group of key value pairs together like this it's called a JSON object and furthermore to create a list of JSON objects use a comma to separate each JSON object and then put a pair of square brackets around the entire list when you organize a list of JSON objects together this way it's called a JSON array and basically that's how data is organized in JSON format key value pairs JSON objects and JSON arrays the only tricky part to keep in mind is that in a key value pair the value isn't limited to being just a piece of text or just a number the value part of a key value pair can also be a whole JSON object or a JSON array in more complex JSON data files or data feeds you'll see JSON data nested several hierarchies deep ok now let's do a practical example of parsing JSON in Swift but before we dive in I just want to mention that support for this video comes from atlanticnet a hosting solution provider for healthcare HIPAA and PCI compliance whether you're starting fresh or need a new provider atlantic dotnet can help you succeed with fully audited solutions and 25 years of experience try atlanticnet to develop test or launch your next project these guys won't let you down right now they're offering a free one gig virtual server with SSDs and block storage for free for a year and free snapshots for one year two plus twenty five dollars in free credits to use on any other services they offer ease of use of something that I like as it frees up my mind to focus on coding I also like that they have round-the-clock phone support so if I happen to get stuck I can contact them easily so visit Atlantic dotnet slash code with Chris and enter the code Chris they get your $25 free credit all right now let's look at parsing JSON with Swift so last week when we talked about api's I used this news API as a demo so this time with parsing JSON in Swift we're gonna use the same API because when you make an API call to the news API such as this one here you get back a really nice JSON result now before we dive into Xcode and take a look at how JSON is parsed and Swift I first want to examine this JSON feed that the API returns and I want to break down some of those things that I mentioned earlier on in this video such as key value pairs JSON objects and JSON arrays so if I collapse this feed you can see that basically this is a JSON object that's what this API call returns and you know this because of these curly brackets containing a group of key value pairs can see here there are three key value pairs all separated by commas exactly like how we described earlier and each key value pair has a key such as status and the value such as okay total results is a key this number is a value and remember when I said key value pairs the value could also be another JSON object or a JSON all right it doesn't just have to be like a piece of text or a number well this is a perfect example articles is a key and the value is actually a JSON array take a look at this there are square brackets here and if you remember earlier on in this video I said that to create a list of JSON objects you surround it by square brackets like this and then inside you have all of your JSON objects separated by commas so let's expand this node and see what we get so if I collapse these JSON objects just so we can have a good idea of what's in here you can see that's exactly what it is that's a JSON object surrounded by curly brackets and then a comma and then the second JSON object and so on and so forth now if you examine actually the data inside these JSON objects you'll see that all of them follow the same format like they have the same collection of key value pairs and that's because each of these JSON objects inside this article's key is an article check this out you have author you have title you have description all of these key value pairs make up the data for a single article and the articles key basically the value for that is a list of articles right it's a list of JSON objects which represent the articles so this is very good information for us when we parse this JSON because when you're parsing JSON you want to think about what it actually is the information that you need to display in your app so in this instance if we were building a news app and we wanted to get a list the articles to display we would really be interested in extracting this information here in this array of JSON objects so how does parsing JSON and Swift actually work well there's something called the codable protocol and it makes it very easy for us to parse this JSON out into useable instances of a structure or a class that we create basically how it works is we map the JSON objects in this JSON feed to structures or classes that we create inside Swift and for each of those classes it's going to represent a different JSON object so take this for instance we have the overall JSON object representing the feed so we're gonna create a structure in our in our project to represent the news feed and that structure is going to have the same properties mapping to these keys right here and then inside here we have these article JSON objects right so we're gonna create an article structure inside our app to map to this data so when we extract this JSON feed we basically use the JSON decoder class and it's gonna try to basically create instances of the articles and instances of the news feed that's basically how it works but it's going to make a lot more sense when we jump into Xcode and I'll show you exactly how easy it is because explaining it like this it's probably a little more abstract so why don't we go ahead and jump into Xcode so right here I've got a brand new Xcode project I don't have anything now let's start by creating those structures that we mentioned to represent the JSON objects in this feed so here this is kind of like the route JSON object which represents the newsfeed so I'm gonna create a new file and as you Swift file I'm going to call this the news feed and I'm going to declare a structure I'm going to call it a news feed it's going to conform to the codable protocol and that's gonna allow the json decoder to attempt to convert this JSON into an instance of this newsfeed structure so I'm gonna create the properties to mount to these keys right here now if there there's a key value pair that you're not really interested in you don't have to create a property mapping to it but I'm going to just do it anyways now when you're working when you're mapping like this and you know that the value for a certain key won't be nil like it won't be empty then I would suggest that you default it to some value like that and the reason I say that is because for example this key right here the value can be null if that is the case if it could be null then you would want to create an optional instead just so when you try to parse that out you're not gonna be trying to insert you know if you default it to a value right here then status can never be nil and if status actually happened to be nil when JSON decoder tries to turn that JSON into an instance of this it's going to not really like that and the way you can find out depending on what API you're working on is just check the documentation so let's take a look at this end point here all right that's the end point the rest are just parameters so this is the everything end point if you go to the documentation and you check out endpoints let's check out the everything endpoint you scroll down here here's some reference about what sort of parameters you can supply into the API call but if you take a look at the response here's status right that's the key and the value can be okay or error so that's good I know it's never going to be nil right so I can safely make this not an optional string same thing with total results I don't think that this would be nil it at least be zero although it doesn't explicitly say that here and as for the keys in the news unfortunately it doesn't tell you if author can be nil or not entitled can be nil or not like is there always going to be a title I'm not sure based on this documentation and we saw from this example out here that under source ID can be known right or nil but here it doesn't it doesn't mention that it could be nil so if I want to be extra safe and I want to prevent crashes during the JSON parsing then you know I could I could just make everything an optional but for the status I'm not going to make it an optional because at least in the documentation it tells me that potential values is only okay or error so that's a little tip for for your JSON parsing okay so let's go back to this so we're building out our newsfeed structure so I've got total results as well and this is going to be an int I'll just default at the zero and then we've got articles now articles is an array of JSON objects representing an article however I haven't created that structure to represent that JSON object yet so I'm gonna leave this as an error unfinished and I'm gonna jump to creating a structure to represent these JSON objects inside which is essentially a single article so let's go ahead and create a second structure and then we'll come back to the newsfeed to finish it off so I'm gonna call this article and this is going to be article and remember it's still gotta follow the codable protocol and then we're going to map these properties to the keys here now I don't really care about the source so I'm just gonna admit that but I do care about author title description URL URL to image published at content all of these are strings so and all of them I'm not sure if they're going to be nil or not based on the documentation like we just checked so all of these are going to be optional strings and I have to make sure that the property names match the keys they don't have to but if you but this is the easier way to do it by just making sure that they match so JSON decoder is gonna just do it automatically and knows which key value pair amounts to which property and it's gonna put the data in the right place otherwise you're gonna have to write a little bit of extra code to tell the JSON decoder what key value pairs match to what properties if that if the names still managed okay so we've got content published that URL to image URL description title and author and I don't care about the source so okay so now we have an article structure that maps to this JSON object right so now I can go back and say that in the news feed that the articles key right isn't a right of our article structure okay so it kind of Maps there and I'm gonna make this like I don't know if this can ever be nil or not the value for articles so to be safe I'm just going to make it optional okay all right so that's basically it so we've created structures to match and map to the JSON objects in the feed now all we have to do is write the Iowas networking code to do the API call get the response back and then we're going to use JSON decoder to parse that JSON data into instances of these two things that we just created so I'm gonna go into view controller and I'm just gonna put it in viewdidload for the purpose of this demo to be quick and easy and as for the Iowa's networking code I'm not gonna go through it in too much detail since the point of this video really is to take a look at JSON parsing so here I'm going to say the API endpoint and I'm going to declare a URL string which is just our API call here now keep in mind that this is not the best practice thing to do to have your endpoint and all the parameters and your API key hard-coded in a string like this but again for the purpose of this demo I am just gonna breeze through this networking code and try explain a little on the way so I'm turning this string into a URL object and using this initializer for the URL object may return a nil-nil URL so I'm gonna write a guard's theme and URL is not know else we're just gonna return and we probably want to log something there to say what happened but at this point we've created a URL object so the next thing to do is to get a URL session and from the session we're able to create a data task we're going to use this method right here by passing in the URL we want to hit and we can also specify a closure or a block of code to run when we get the response back alright so this is gonna actually hit that make that API call and then run this code block when we get the response back and inside that code block is where we're gonna do our JSON parsing notice in this response sorry in this block of code we have a couple of input parameters that come back to us we have the actual JSON data we have their response from the server and we also have a parameter representing any error that might happen so let's go ahead and do that and now here I'm gonna pass in the URL I'm gonna force unwrap it because we checked that it's not nil already and for this closure I'm gonna double click it to open up a closure and I'm going to name these parameters so data is our JSON data that comes back response is going to be response object and this is just going to be an error inside here we're going to just check for errors now I'm gonna check if if the error is nil I'm meaning that there is no error because if some something happened and there is an error then this wouldn't be nil this would contain the error object and we could take a look at what there is so I just want to check that it is nil meaning there's no errors and I want to check that the data is not nil meaning that there is some JSON data that comes back because now I would parse the JSON there's no errors and there is JSON data to parse before I jump into there I always forget this part if I don't do it immediately so in order to actually fire off the data task loops you're gonna call theta toss stop resume okay so for parsing JSON this is the fun part this is the part where we are all waiting for so let decoder equals JSON decoder I'm going to create a new instance of that and then for decoder I'm going to use the method right here decode now there are a couple of things I want to point out here we're specifying the the type that we're trying to parse the JSON data into and so for us that would be an instance of newsfeed right because we created this just to map to this right so it's going to attempt to convert this JSON into an instance of newsfeed so that's why we're passing news feed in there let me just open up that again from the here's where we pass in the JSON data and notice that it throws that means that potentially it can throw an error in the process of parsing then and then we're gonna have to wrap that in a do catch block just because it throws and we're gonna have to use the try keyword to try to run this method and that's kind of like our error handling if there's an error that gets thrown we're gonna capture it gracefully show a message or something or log it and that's what that throws keyword means so let's go ahead and now implement it so by passing in the type you're gonna have to write the class name or the structure named itself and then here we're gonna pass in the data I'm gonna force unwrap it yeah and we're gonna have to try to do that and I'm going to set the result of the parsing in to a constant called newsfeed all right so let's wrap this in a do catch block and in here you know error in JSON parsing so we'll just set a breakpoint there and here we'll just print the news feed you know set a breakpoint there and I'll set a breakpoint right there for when the response comes back and we'll run this and take a look at what happens at night just let me double check we've got everything here we'll just indent that yeah I think so so let's go ahead and run this project again you in your app you wouldn't do this in the new and the view didn't load and you would probably be a little more descriptive in you know your error handling these are not very descriptive but let's see what we get alright so basically it's sent off the API call it's come back and here we're running that closure after the responses come back so here we're going to check if there are any errors and you can even see down here that there is data and there are no errors so it's gonna go through that and then this is going to create the decoder and this is actually going to do the parsing all right so this is the moment of truth a step over that and let's take a look at what's a news feed now as we're at this point right here so I'm gonna say P own news feed cool so it looks like we do we have gotten our our stuff so the status is okay did I capture the status yeah so we do have stats okay so we have statuses okay total results it's 4622 and the articles array contains 20 articles now let's go inside and check all you see author can be nil I wonder if that's true there I messed that up okay the title is Genesis announces record-breaking quarter let's take a look at what's here let me just refresh this ya see the author can be nil and they never mentioned this in in the documentation see an author here they should have I think they should have mentioned that it's just so good thing that in the article we made this an optional okay anyway so let's go back to this so it looks like our parsing worked and it was so simple right we have the description we have the URL the URL to the image and published at so we could convert that to a real date and we have the content yeah so that's that's exactly how easy it is to parse JSON in Swift and just to remind you guys what happened here we basically created structures to map to the JSON objects in the JSON feed and then we used JSON decoder and we passed in the type we wanted to try to convert the JSON data into and we just let it do its magic thank you for commenting on last week letting me know which api's you wanted me to see a demo of integrating with in today's video I want to ask you guys to do the same let me know below in the comment section if there's a specific API you'd like to see a demo of me integrating with because next week I'm going to start looking through those comments and choosing some api's to work with and do tutorials off of if you want to support this channel please don't forget to give this video a thumbs up and hit that subscribe button if you haven't already tap on that Bell notification icon so you don't miss the next video thanks for watching and I'll see you in the next lesson
Info
Channel: CodeWithChris
Views: 66,094
Rating: undefined out of 5
Keywords: what is json, parse json, json parsing, how to parse json, codable swift, what is json parsing, codable protocol, json parsing in swift, json parsing tutorial, how to parse json in swift, json, json tutorial, json explained, json tutorial for beginners, learn json, json parsing example, json parsing swift 4, xcode, programming, swift
Id: _TrPJQWD8qs
Channel Id: undefined
Length: 24min 14sec (1454 seconds)
Published: Fri Feb 07 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.