Previous episode: 05. Make a Network Call
Next episode: 07. Challenge: Add More Properties
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
In the last episode, you made a network request and receive data back by way of JSON. JSON groups responses into objects and lists of objects. The objects are indicated by curly braces while the list of objects are created using square brackets. Objects and lists can be nested inside of another. The raywenderlich.com API returns a list of courses in JSON. Each course has an ID and attributes. In this episode, you'll see how to parse the API response JSON into model objects. Okay, let's take a look at the JSON we are planning on accessing. Copy the URL to a browser, and you'll get a whole bunch of JSON. I'm using Firefox that automatically formats the JSON. But if you find yourself staring at a wall of text, then you can simply search for a JSON formatter and paste the JSON into it. You'll notice that at the top level, we have a data object that contains a number of episodes. Each episode contains an ID and a type. There are also a few subcategories. The important category is the attributes category. It contains all the information about the episode. You'll use the attributes to populate your data object. Let's get working. Open up your project in progress, or download the starter project for this episode. First, we want to create a course from the JSON. A good place to do this is in the course object itself. In the model folder, open up course.dart. Add a fromJson method. When you convert JSON, you'll get a map. The map keys are Strings, and the values are dynamic. They're dynamic because JSON contains several different types, and you won't know the exact type until runtime. Populate the course data by extracting from the JSON. You'll do this in a constructor method, passing in the JSON. Add a toString override. Now, to create a course from the JSON, in the repository folder, open up course_repository.dart. Replace print with a call to from JSON, and add the rest to the list of courses. Now, in the courses folder, update course_page.dart to print out the course name. Run the app. Now, instead of getting texts to the console, you have lots of texts printed on the screen.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.