2 The Basics of JSON Decoding - Swift

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi my name's Stuart Lynch and this is the second of a nine part series on understanding how to parse JSON using the codable protocol in swift and swift UI in this video we'll explore the basics of decoding JSON we'll start with simple JSON objects and the decodable protocol we'll look at having optional properties we'll take a look at JSON arrays and more complex objects and finish with some strategies on building your structs and classes based on the JSON data structure this is something that you're interested in keep watching first of all if you want to work along with me be sure to download the starter project a link is in the notes below it's an Xcode playground that has multiple files that we'll be using for the next seven videos if the file on your Xcode project doesn't look like this then you need to make sure that first of all you choose to show rendered markup from the Edit menu and also make sure that you show the left sidebar now the first page is this introduction page that you can use to navigate to the different pages each one will be a different video in this series each page also has navigation that lets you go to the previous and next page or back home to this introduction or table of contents you can also navigate by clicking on the files in the sidebar let's get started by getting down to basics and decoding a simple JSON structure before we start looking at decoding JSON from a file or an API let's just first look at how we can decode JSON from some strings with Xcode we can represent multi-line strings by enclosing the lines within triple quotes so for our purposes what we need to focus on is the structure between the triple quotes here we have two structures person one JSON and person two JSON they're almost identical but the second is missing the partner key value pair if we want to decode this data we need to make sure that we take care of that but I'm getting ahead of myself first let me build a struct that represents this first object we can simply create properties that use the key values as the variable or constant name and then define the type as we see it for example name is string age is an int and so on if we want to be able to decode JSON using this struct we must make the struct conform to the decodable protocol for a struct to be decodable all of its properties have to be decodable as well fortunately for us all of the basic Swift types are already decodable so we don't have to do anything else if a properties type is not decodable xcode will let you know and we'll have to define our own coding keys to accommodate that and we'll take a look at that shortly so how do we decode we'll be repeating this process many times but it goes like this first of all we normally define a constant decoder as the json decoder the json decoder requires a data object to decode but our two constants are strings later on in this series we'll be getting our JSON from a file or from an API request in which case you already have a data object but to start out so we can work in the playground we're starting with strings that need to be converted to data objects we can use a single line of code to get the data and assign it to a new constant that we can then decode when converting a string into data the return type is optional but you can safely for son rabbit strings in Swift our unicode internally so encoding a string using a Unicode encoding will always succeed the next step is to decode the data using our decoder we want to decode the object into a person struct so we use person dot self here our decoder is decoding from our data into a person now this decoding procedure can fail so we have to use try and to be safe we should use an optional try-catch block but we'll get to that shortly so let's assume that our data is good and just use try exclamation mark so no need for a do catch block now let's print out person 1 name and person 1 dot partner both there okay well let's try the same for person to remember a person too is missing the partner and key value pair will just duplicate and change the number to two we can use the same decoder but we get a fatal error as we'd expect because the second object has something missing this is easy enough to fix though we just changed the partner property to an optional and run again it works though we do get the optional keyword that we'll have to deal with and we get a couple of warnings but I'm not going to worry about that right now let's move on but first let's comment out this print statements so that we can see what's going on in the console for the next example in the last example we looked at two different JSON objects we did that for comparison what if we put both of these objects into an array can we decode these of course we can this is valid JSON so we should be able to decode it just fine we already have our person struct so we can use it again let's go through the process convert our strength to data and assign it to a constant called person JSON data next we can use our decoder to decode the data into an array we're decoding from the person's JSON data and putting it into an array of person don't forget to always add dot self let's loop through the data now and information this time we know that the partner is optional so let's handle that case with a no coalescing operator and assign the value of none to the person top partner if it's nil great we're on a roll now we've never used the person's sign and likely never will so even though that's part of the JSON object and one of the key value pairs there is no need to decode it so we can eliminate it from our struct you can pick and choose which values from the JSON feed that you wish to decode and build your structs or classes accordingly running once more we see no errors moving on let's look at this more complex object it has two keys family name which is a string and members which is an array of JSON objects these Jason objects just happened to be our person objects which we already have a struct for so we can define our decodable struct for family like this this works because string is decodable and we already know that person is decodable too so here we go again with our procedure we convert the string to data using utf-8 we try to decode the data and this time we are going from family JSON to a single family JSON object and we can print my family name and then loop through each of the members of the family and print their names as we see we get our family Smith and the two persons James and Mary in the real world you won't likely have one of these trucks already created like we had with our person struct so let's see how we should really deal with this JSON when we're building our structs our classes but first let's comment out these sprint statements I'm going to start off the same way but call my struct family too and make sure it's a decodable struct the family name key is still going to be the family name string property but I want to define my person object within the family - struct so I'll just copy from before and paste it here now I can define members as an array of this person struct notice we're picking family to dot person as the struct the family to part can be left out because it will look inside the parent struct for a match first before going outside to look for any others of the same name now one more thing I realized that gender is always going to be one of three options male female or other so include a new enum to cover this and make it string and decodable by having a raw value type like string and adopting decodable in its declaration gender automatically conforms to decodable without any additional code so I can change gender now to type gender the family JSON hasn't changed but we can copy the decoder and print statement and loop and just change the constant and struck to add a number two to it to reflect our new struct and constant running once more we see we get the same results seeing that the raw value from the enum gets decoded properly as a stream I hope you've enjoyed this video and have learned something if you did please give it a thumbs up and subscribe to my channel that will encourage me to keep on creating more like this in an effort to help new and existing iOS developers hone their skills and move on to the next level I am most active on Twitter so be sure to follow me there and get all the latest news of what I'm up to
Info
Channel: Stewart Lynch
Views: 2,496
Rating: undefined out of 5
Keywords: Swift, Xcode, JSON, Codable
Id: 34U5CPpfORs
Channel Id: undefined
Length: 10min 46sec (646 seconds)
Published: Sun Feb 09 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.