Parsing JSON Just Became Super Easy in Swift 4 with Decodable

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys welcome back to the channel hope you guys are doing well today and hope you're ready to learn a little bit more on how to actually code in switz in today's video pretty excited too I kind of talked to you guys about how to parse JSON very very easily using just one line of code so we're going to do this in Swift for using something called a decodable protocol and it's going to make your code very very simple and also a super super straightforward and along the way it's also going to make your code very very easy to maintain and you guys know how much i like to talk about code maintainability so let's get started today with a quick quick example and see what we can do with JSON and then we'll dive straight into the parsing exercises okay so let's kind of look at what we have on the screen and we have the Chrome browser on the left side with some JSON right here that's pretty complicated and we'll talk about this in just a bit let's look at the app in the simulator which is something we built out in early 2016 I believe and it is very similar to the App Store that everyone should be very very familiar with okay so you want to check it out make sure to dig through the archives of this channel and you should be able to find it and basically we were able to build out this entire app using this JSON on the left side so you see battery category enhance with three touch this icon right here and to build out the list down below best news apps investment game we have this categories array which is best new apps right there and then best these games like that which is okay so right off the bat you'll notice that but JSON here is pretty complicated we have this chunk and then we have this chunk and so to parse all this out we have to write a lot of JSON parsing code so that's not always all that hard a bit is not that fun either so today's video I want to show you guys how to parse out this entire bit you can just want one line of code and it's going to be very very easy so before we can kind of learn how to do this let's start out with something very very simple which is at this URL right here API dot let's build that app / JSON decodable / course and this represents a very simple course object with an ID a name a link and an image URL so I want to show you how to parse this out and right now using this app that I have in the back which is just a single view application I'm just going to run it to show you that it does absolutely nothing so we just get a white screen and we're kind of ready to look at what we want to do here so we have this course model object and typically when you're parsing out JSON inside of your app you have a model object that reflects what that JSON is let's just create this model object called course and inside it has an ID of int and then it has any of these other properties such as name link and image URL so let me type that out real fast with a light name via type string let's link via type string as well as not only URL image URL bf type string like so alright so what can I do this guy love you can run a very very simple example down here with perhaps let my course equals this course object with this constructor that Swift gives you automatically and let's just use one and perhaps my course and then some link and then some image URL finally to kind of show you guys what this does I will print it out with a print statement and run the obligation out and then down below we see the description as to what this course is right here so pretty good stuff and now that we are ready with this course model object let's take a look at how to actually fetch this bit of data at this URL so let me just copy that so can see and then let's see down here I will say perhaps let JSON your l string equals all that and perhaps we need d s right there and so what can we do well we actually need to execute some kind of your sessions you fetched this data from the internet and you need to say URL sessions that shared data tasks with this completion Handler and its URL we need to construct it right above so let me say I let URL equals this URL with this constructor and let's see down here we have this string constructor I'll use the JSON URL string from above and then right here you can just fill this out with this URL all right for the completion the headline does hit enter and then fill out these first three parameters with data and perhaps response and eerr for the air it doesn't exactly matter what you call it but now you want to you know perhaps check your arm and then also Lido perhaps check response that is a 200 ok let's type that out and then you are kind of ready to start doing stuff so do stuff here and the last bit of code that you need to type out is to actually hit dot resume on this URL session so you make sure you fire it off okay so that's that and there's this error right here you're about to fixing this URL because it's not unwrapped yet so to do this correctly let's just use a card let optional binding and if that doesn't work we just return out of you didn't load so I'm going to run this app now and perhaps put line breakpoint on line 29 and you'll see that it hits the breakpoint right now and there it is if you continue we get the G stuff here Prince David right below so really good stuff okay so let's go ahead and remove this print statement right there and actually see what we can do with this data object that we get back from this URL session call so I want to show you guys how to print out this data as a string with a string constructor like so and this constructor using perhaps this data a guy and we need to get an A not an honorable version of this data right there I'm wanting to use garnett optional binding again current let data equals data otherwise we will return and then we fill this guy with that data and encoding hit dot and you should be able to get utf-8 all right so let's print out what data a string is right now by running the application and you will get this morning but down below will get the optional string of the bit of JSON that we're looking at right here ID name and link an image URL like so alright so to make this example a little bit more interesting let me show you how much work it takes to parse out JSON using the methods of switch to and flip 3 so let's say right here what we need to do is to not kind of serialize this data object up here into some kind of JSON object using JSON serialization and use the method call of JSON object with some kind of data and then right here the options is perhaps mutable containers and then right here you can actually have to print out what this JSON guy is and got to build this it actually doesn't work because me to handle this potential error with a do catch and a try so do catch perhaps let JSON here and you need to put all of this inside the view and then right here you can just say try and I will comment out those two lines and run the code right now so if I put a breakpoint on line 37 it will hit this right there hit the continue and then we get the actual serialized bit of data in this format like so and just pretty much represents what we have right here okay so if it's Def and inside of this catch we should actually print out you know air as serialize being a JSON and then wraps hit a comma and JSON air like so alright so what we can do now is to use this JSON somehow and construct the course object that we need which looks like that and of course object is this course struct up here so the way I do traditional JSON parsing looks like is you first create some kind of constructor using and it like that and you see Jace on a perhaps string to any and then down here you would say id equals JSON and you have just use the idea stream to access the dictionary or the ID inside of this dictionary and youa cast it into you and in and you would otherwise give it some kind of default value if it's not able to do so and then you would do the same thing with the names of equals JSON and perhaps name as string and you would default at these some kind of empty string now it's not only you need to do all this for all the properties inside of this struct so I'm just going to do this rather quickly build everything should be fine okay so once you have that constructor you can just a let course equals course and just use the JSON that you serialized from line 43 and then finally you can print out what course dot name is perhaps and then finally when you try to build your project you get this error where you need to cast this JSON object into a string to any guy like that so I'm going to do this the safe way of using a guard let's and with this cast is to a string to any otherwise we return we can run the project now but at breakpoint on line 46 and then you see exactly what this course object is down here so of course is right here and it was able to use parse it successfully into the ID name link and image URL which DC name is Instagram firebase and that's exactly what that is alright so there will be more traditional way of performing JSON parsing using so 2 so 3 and also objective-c let me just write that here so 2 3 and Objective C and while I'm at it I'll just comment all that code out and assure you guys how much easier it's gotten by using a little bit of magic with so forth and also Xcode 9 beta right here and the first thing I do is to say let course equals some kind of objects using JSON decoder and let's use an empty constructor and now we can decode this object by calling decode which expects some kind of type of decodable dot protocol and then on the right side right here this data is the exact same thing that we'll use before so let's just paste that in there and the question now is what the heck is this decodable protocol well json decoder is actually very very simple to use and all you need to do is to feed in the model object that you're trying to parse your JSON into so the way it works is first you have to conform your model object to the decodable protocol and then down here in the decode method you just pass in the core spots so and then it in the very front right here you want to make sure you a try because decode can actually potentially throw you in here and then you can automatically write here call course dot name inside of your print statement and i'll put a breakpoint on line 44 and run the application to show you exactly what we get okay so JSON decode has decoded everything inside of our data into this course object right here with the idea one Instagram firebase the name the link and the image URL so really really easy stuff and it kind of allows us to remove some more code which is up here so I'm going to go ahead and go ahead and remove the initializer inside of our course model object and rerun the application to show you we don't need this constructor anymore what is kind of happening underneath the hood is that this course right now JSON decoder is actually able to decode it by simply setting up all the properties automatically based on what is inside of this JSON object so as long as your properties match up with what is in the actual JSON blob you should be okay all right so that's how it works inside of so it's for now and it's much much easier you can just add in properties that you perhaps we'll add in later when your JSON becomes in even more complicated so let's now move on to something a little bit more difficult and move on to the second tab right here so the URL is exactly the same but this is now courses and we just pull this up a little bit so you can see and instead of having just one course which looks like this we now have an array of courses so as you can imagine this is a little bit more difficult but using this what's for this is also very very simple and we have to make a minor modification to the decoding process and pass it in a right of course instead of just a simple course so let's go down here JSON decoder decode and put in right here a bracket and it's Bakula gland and now we can print out what courses is so I'm just rename the variable two courses and we will get an array of course is when we print out this down below but instead we get this error and the reason is because we haven't exactly changed the URL yet so I'm going to just put it s right there and we will now parse out the JSON that is coming back to us in this a ready form which now looks like this so you see course ID name Instagram firebase and then this other course right here with ID 2 and Kindle basic train which ours is these to consider here id-1 id2 and the name link and in the URL like so right here and now the final thing I want to show you how to do is to parse out an even more complicated JSON blob which is this right here website description and this JSON object has a name has a description right here and then a courses array like this which contains the two previous courses instead of this array right here so how do we do this very very easily using this list forth well let me show you right here and the first thing we need to do is to construct some kind of model object that has this structure so let me use another struct which I will construct up here and let's say struct and let's use website description and what kind of properties do we need well let me just use main description and of course is so let's see let may be a type string and let description be of type string and let courses be of something well if something is going to be at a rate of courses like so and that's exactly what that needs to be and I'm going to modify the URL first so website description let me just paste that into this URL for the JSON URL and then down at the very bottom all you have to do is to either modify this or you can type out something else so and just comment that out and let's just do this one more time website description equals JSON decoder empty constructor decode and we need to pass in the type of website description when you type out the capitalized class and not self and I use B data from above so if you got to build this it doesn't work yet because website description needs to component to the decodable protocol so let's do that one more time for this struct so let's use decodable and now you should be able to run your project build I believe we need to try right there let's print out what website description is and I will let's say you've made a website description like so cleared out to see what we get down below so let's see right there let's build that app teaching building absent 1999 which are these two properties right here name and descriptive you can also print out the courses if you wish to do so alright so that's pretty good and one last thing I want to kind of warn you about is that sometimes only JSON blob such as this sometimes it might not contain all the properties that you're expecting so for example you can have certain JSON blobs that are missing shield so this is courses underscore missing steel at some times your courses might not have an ID or a link or imageurl such as this last course right here so this yelp course so the idea is in order to kind of cope with this problem you have to actually do something else that's a little bit strange with your struct objects it is also pretty simple so let me just copy this chunk and see what happens when I try to parse that so I'm just going to replace website description with course missing field and let me comment out this guy and basically this is an array of courses so I'm going to use the courses decoder right here and kind of print out what the decode is and instead of having it work it's actually going to fail because the JSON is missing some properties so this key not down when expecting non-optional type int for coding key ID basically it's saying that this Yale course is missing an ID so how do we actually fix that all you have to do is to make your properties optional optional string like so and rerun the application and it should be able to parse all of the missing properties correctly down below so you see this right here and then the final course is just ID nil name is young link is nil and image URL is nil and it kind of reflects what you have inside of this JSON blob all right so JSON parsing now has become super super easy to perform and probably no longer need all of those special cocoapod libraries that you're used to using also the links to all of these dates are URLs that I showed you today is available down in the description below as well as the source code for today's project in today's video and if you're really really interested in finding out how the JSON parsing works in the App Store applications that I showed you in the beginning you can find the source code in the description as well that's not only make sure to give the video a thumbs up if you enjoyed it subscribe to the channel if you haven't done so already for more videos like this and I will hopefully see you in the next video bye guys [Music]
Info
Channel: Lets Build That App
Views: 266,233
Rating: undefined out of 5
Keywords: ios, swift, development, tutorial, learn, xcode, programming, code
Id: YY3bTxgxWss
Channel Id: undefined
Length: 19min 29sec (1169 seconds)
Published: Sat Jul 01 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.