How To Parse JSON Using Codable

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome back to another code for our tutorial in today's lesson we are going to learn how to parse JSON using the codable protocol from Apple so where you had to use third-party frameworks before well you can throw those away because codable takes care of everything for us if you're new iOS developer just getting started make sure you check out my iOS development fundamentals of course you can find links for that down below in the description it's a great course it'll help you a lot you can save 50% off if you use my sign up links so make sure you check that out so let's go ahead and get started JSON parsing is an incredibly common thing that we need to do in mobile development and one of the things that Apple introduced in Swift for is this new protocol called codable or really it's a type alias for the protocols decodable and encode Abul and so what this is is it's an inbuilt way to serialize and deserialize objects to and from json format built directly into Swift without having to use a third-party library so you are probably familiar with maybe swiftie JSON for example or maybe object mapper or mantle if you're working in Objective C and those are just one of many third-party libraries that we've used for a while or we've had to roll our own you know using JSON object which can get kind of messy but now a lot of this can be handled using Apple api's and Swift so if we take a look a little bit through the documentation here going into the encoding and decoding custom types there's more examples of how to use these protocols and really what they encode and decode and so one of the important things to understand is that any data type in a JSON response that could be a string an int a double date data URL all of these primitive types can be encoded and decoded using these protocols so what we'll do in this tutorial is go through a few examples in a few use cases of how to encode and decode and see a lot of the value that we can get from using this built directly into Swift and not having to use a lot of these third-party frameworks that we used in the past so I'm gonna Swift playground here and in case you're wondering why my version of Xcode looks a little bit different than yours it's because I am in the Xcode 10 beta which has the dark theme going on in Mac OS Mohave so that's why my Xcode looks pretty cool and yours will - in about a month or so and the final release comes out but so what I've got in front of me here is a very simple example that we'll start from and then build up to more complex ones going forward and this is just a single dictionary and you know JSON format really it's just something that represents a food or a fruit so this is just a food name banana with another property calories which is an integer type and this is a string type so what we'll start off doing first is we're gonna create something that informs conforms to the codable or it being credible decodable protocols so I'll start off using a class first and we'll just create a class called food that conforms to the codable protocol I'll go ahead and give this some properties food name and calories which is a type of int and this is a type of the string just like that we'll go ahead and create an initializer and now all set there so right away we have a very basic data structure that conforms to this codable protocol that we were talking about in the beginning and if your commands click uncodable you can actually go into the class and and read all of the things going on inside of it's all the documentation properties understand the protocols and stuff but let's go back and just run through a very simple example here so okay we've got our class to find the next thing we need to do is if we wanted to decode this JSON into this class we need to create a JSON decoder so what we can do here is create a new property let food decoder equals JSON decoder like that and then what we'll do here is create a do catch block because this is something that can throw an exception if it's not handled properly and we'll do here is inside the do block we'll do a left food result equals try the food decoder dot decode and you can see here that it takes two parameters there is the decodable protocol and then the data so in our case here we're going to use this this single Dyck JSON which I've already converted to data type by the dot data using utf-8 format here so all I can do is just copy in the single dict property from here and then what we'll do here for the protocol is we're going to say food dot self and the reason why this works is because food is conforming to decodable through the codable protocol here which is a type alias for both of them so what we'll end up doing now is printing food result dot name and print food result dot calories right and I was good and also throw in a print here if we blow up failed to decode the fruit or the food sorry like that no print ad description there so let's go ahead and run this playground up to line 30 here line 32 and you can see here that the food name banana and 100 are being printed out in the console so great it looked like that was pretty easy to do now what would happen if I I don't know I changed let's say I removed calories completely from the JSON and I go ahead and try to do this again well we're going to hit an exception because the format is incorrect and if I made this optional however and something like that were to happen where an element in the JSON payload disappeared let's see what happens in this scenario now in this scenario obviously we don't crash or throw catch an exception but we'll get back a nil value for calories here because it wasn't included in the JSON structure here so that's just something to be mindful of working through some of these parse some of the parse so we've seen how to do a basic decode now let's look at an example of in actual basic encoding so I'll go ahead and get that set up right now so really what we just exercised previously was the decodable protocol so now we're going to work the encode Abul protocol by actually generating some JSON from a model so we'll start off by creating a new food let's just create a strawberry for example or how about an apple let Apple equal food give it a name Apple say it's 80 calories like that and after that we'll go ahead and create a JSON encoder so let JSON encoder equals JSON encoder like that and then you can set the format of the encoder now put formatting dot pretty printed for just printing in the console and the next thing we do is we'll do something similar we'll do an encoding so we'll start off with a do catch block and we catch anything that blows up feel it's going to code the food I'll just print out the error localized description if any and well now we'll do the encoding inside the do block so we'll do let JSON equals try JSON encoder dot encode and it needs to be something that conforms to the incredible protocol you can see here with the value right so by passing in the actual Apple food that I created from up above that's fine it satisfies that requirement because it conforms to encode a bowl via the codable protocol type alias so now what we can do is we can just try to get the JSON string that's really JSON data so I should say JSON data here and we'll just do from data here the actual JSON data with the encoding utf-8 and if that works then we'll print out the string like so and now let's go ahead and run this and see what we get and so sure enough that works you can see down here in my console you'll see if I can expand this it's that's even better to read when I print it the calories 80 the food name Apple so that's how easy it is to go back and forth from encoding to decoding with a very simple structure but obviously in the real world our JSON is going to be a little bit more complex than this we're probably gonna have arrays of things nested structures so those are the examples that we'll we'll take a look at how to tackle next all right so moving on the part two so now I've set up a second JSON structure here and this is going to be decoding or I guess encoding an array of dictionaries with possible nesting so we have this dog owner JSON data and if we look at the format of this here we have an array of dictionaries the array is denoted by the square bracket here and then the dictionary is by the curly brace here so this is one dictionary and this is also another dictionary however inside of this first entry here we have some nesting going on with another array of dictionaries so the structure is pretty simple you have a name age an array of dogs because these are dog owners you have a dog with a name a breed and an age and then the possibility of not having any dogs for some people because our second example here doesn't contain any dogs so how could we model this using the ncredible decodable protocols so right below our JSON here let's go ahead and start modeling everything and we'll start from the dog well modeled that and then we'll work back up to the dog owner and model that as well and also feel free to pause the video if you want to take some time to copy this JSON or create your own before moving forward so let's go here and start off with the dog now I use the class before but structs work just fine so we'll use trucks for this example so struct dog which conforms to codable will have a name a breed and an age which will be an integer type and below dog will do another struct called owner which also conforms decodable owner is going to have a name and age and an array of dogs however the market is optional because if we don't mark this as optional any entries that we're reading in for example this person lives doesn't have any dogs so we're gonna crash in that scenario here based on how we map this if this isn't optional in this in this particular scenario so let's move on to the decoding first we'll go down and create our decoder so start with the JSON decoder and create our do catch block because this could blow up and now we'll go back in the do block here and actually start working it so we'll start off with a let dog owners equal try dog phone or decoder dot decode which if I can get that autocomplete working here no okay that's fine and what I need here is the dog owner JSON data so dog owner and JSON data is we're gonna pass in and for the first parameter that's going to be an array so we need to do a array of owners because it's going to be a from that protocol dot self and that will satisfy that decodable protocol requirement there now let me see here if I have a problem and I do this type variable name okay we should be good there and so what we can do now is what are we left with we are left with an array of dog owners and you can see here that it's up type owner so we can iterate through this we can go for owner in dog owners and then we can march on down here so we're printing the owner name is owner dot name and we can do a conditional check if let dogs equals owner dogs because we marked it as optional and we'll do another check here because let me show you that you can you can still add an empty array to that got to make sure we make sure we have valid instances of dogs in there so if let dogs and dogs count it's greater than zero for a dog in dog this will print them out dog name then I guess we can format this to make it a little bit more readable dog name and on to age dog age and then finally breed like that dog dog breed so that's good there we can print out all the dogs and otherwise if they don't just do an L to catch in here print the owner doesn't have any dogs okay so look we're looking good we're looking good we're letting go we think we're looking good let's go ahead and give this a shot and see what happens so good hits play button yeah Oh looks like something blew up fail to decode the dog's JSON the data couldn't be read because it's missing well that seems a little strange seems like everything is right we go back and we look at dog and we see okay looks like all our properties are here and then we we go back up and we look at our JSON and then something comes to mind this is different than everything else dog underscore name not the knot name so that this is something that we have to pay attention to and it's an easy solution for what we can do is we can create what's called a coding key and we can create an enum inside of the struct dog private Inu coding keys string which comes from coding key and what we can define what we can basically ver say is hey for the property name I want it to map to dog underscore name like that right and you have to actually map all the names here for your variables so you're gonna have to do case breed although I'm not gonna map that's anything different because I it's exactly grade here is the key is exactly the name of the property here but name is not the same as dog underscore name so I have to create a mapping there which is why I had to do this but satisfied the protocol have to include all the properties as case statements and now let's go ahead and try that again with our mapping in place and see what happens and so it looks like that worked let's go ahead and see if we can expand these playground lines in here so we've got see here the dog precious age three breed pug dog named Furby h5 German Shepherd and then Liz who doesn't have any dogs so that gets printed out right here so you can see that hey that worked and we learned that we have to use coding keys to make mappings for keys and JSON that don't have a one-to-one naming with what we have in our structure class data structures so now let's move on to the example where we would work on the encoder both side of this generating JSON from our models so one other scenario when I call out is the scenario where the let's say our web service gives us back an empty collection of dogs here now since we marked this optional and we check the counts greater than Z unless you see what happens if we got back into empty array instead of the array of dictionaries that we were expecting to receive so we run this here let's see what we got so John who obviously had dogs before I removed them doesn't have any dogs Liz who never had any dogs doesn't have any dogs so we handled that scenario just fine by marking that optional and checking that the count needs to be greater than zero for the dogs now let's go back to the encoding part so for the final part of this tutorial we'll go ahead and handle the encoding of the potentially nested structures so we'll start off creating our encoder like we did before let dog owner encoder equals a JSON encoder and we'll set the format overriding create one so we'll create an instance of a dog owner once it's it's mark 45 say he has a dog that dog will be named Mikey will be a boxer and we'll say it's two years old right and since it's an array I've got to put that inside the brackets there make sure that's syntactically correct and let's go ahead and create our do block do catch builds to code leave dog owner like that and but encoded or how about this let dog on your JSON data equals try dog owner encoder stopped and cooed dog owner like that and then we need to get the string representation of stat back so if I want the JSON if let JSON string equals string for data which is a utf-8 lift-up print it out in the console here okay let's go ahead and run this and so far so good so we have mark 45 he's got some dogs or one dog the boxer named Mike and you can see that that JSON is being printed out right here in that nice pretty print format so in again because we said that his dogs can be nil we can we can do this pass and nail for it and now when we do that we're just gonna get back mark you know name and age 45 what if we just do an empty collection of dogs instead like that see what we got and it'll pass the you know it'll get converted to JSON but you can see here that the dogs is an empty collection and it's because we didn't give any values to it so one final point before we wrap this up is you know you can see here that you can do a lot with these protocols and I didn't really do any customization I didn't conform to D codable or codable uncodable specifically to do some more at work on maybe some advanced mappings because even still these mappings are you know more advanced than the first one but they're still pretty basic in the grand scheme of what you can get back from web services and so they even these scenarios might fall apart under certain situations so how you map these how you model these is important and having an understanding how to do that is gonna be kind of critical going forward so for simple structures you can just conform to codable like I did here maybe create some mapping keys and you're good to go but for more advanced things you may need to conform to encode Abul or decodable directly and actually do some work there creating initiative doing work and the initializers the protocol creating other you know other things other mappings that are going on and so if you go back to the encoding and decoding custom types from Apple developer documentation if you scroll down to the related documentation there's a section here called - using JSON with custom types it this goes into a more complicated example of scenarios that I didn't cover this tutorial just because it's a little bit out of scope it is more advanced but for for more difficult things to map this may be a good reference to figure out how to do it but it's not that much more complicated it's just you have to consider edge cases and things that you may not have thought of in your original mapping so even in third-party frameworks you're more than likely gonna have to handle something that's a little bit out of the norm just like you'd have to do it in these scenarios the benefit is doing it the Apple way is you are eliminating at their party framework you're not having to maintain that curve you're not taking any risks if there's defects in their code apples code is usually say if they're frameworks are usually pretty consistent so there's just some serious advantages that you can gain from eliminating any third party JSON frameworks and moving you know full steam ahead with the Apple api's and their reps of this tutorial if you found this tutorial helpful let me know don't smash that like button and consider subscribing the code Pro stay up to date for all the latest tutorials you can follow me on facebook on twitter on Skillshare and then new to me and let me know in the comment section down below what tutorial you guys would like to see next thank you so much for stopping by and I'll catch you in the next one [Music]
Info
Channel: Code Pro
Views: 9,375
Rating: undefined out of 5
Keywords: How to parse json using Codable, how to parse json in swift, how to use decodable, how to use encodable, how to use jsondecoder swift 4, how to use jsonencoder swift 4, parse json codable, parse json swift 4, codable, codable swift, codable swift 4, swift 4 json, swift 4 json encoder, swift 4 json parsing, code pro tutorial, codepro tutorial, ios development, ios tutorial, swift 4 decodable, swift 4 encodable, swift 4 jsondecoder, swift 4 post request, swift tutorial
Id: Oj-2s0ALACE
Channel Id: undefined
Length: 26min 16sec (1576 seconds)
Published: Mon Aug 13 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.