This video Parse the Network Response was last updated on Nov 30 2021
In the last episode, you made a network request and received data back by way of JSON. JSON groups responses into objects and lists of objects. The objects are indicated by curly braces, while lists of objects are created using square brackets. Objects and lists can be nested inside one another.
The raywenderlich 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 that we are planning on accessing. To do this, first copy the json url from the course repository.
https://api.raywenderlich.com/api/contents?filter[content_types][]=collection
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 is the attributes category. It contains all the information about the episode. We’ll use the attributes to populate your data object.
Let’s get working. Open your project in progress or download the starter project. First we want to create a course from JSON. A good place to do this is in the Course object. In the model folder, open course.dart
. Add a fromJSON() method.
Course.fromJson(Map<String, dynamic> json);
When you convert json, you get a Map. The map keys are strings and the values are dynamic. They are dynamic because JSON contains several different types. Populate the course data by extracting from the JSON. We’ll do this in a constructor method, passing in the JSON.
Course.fromJson(Map<String, dynamic> json)
: courseId = json['id'] as String,
name = json['attributes']['name'] as String,
description = json['attributes']['description_plain_text'] as String;
Add a toString override that you can use to see string representation of the course class.
@override
String toString() {
return name;
}
Now to create a course from the json. In the repository folder, open course_repository.dart
. Replace print with a call to fromJSON, and add the rest to the list of courses.
final data = apiResponse['data'] as List;
for (final json in data) {
courses.add(Course.fromJson(json as Map<String, dynamic>));
}
Now in the courses folder, update courses_page.dart
to print out the course name.
if (courses == null) {
return const Center(child: CircularProgressIndicator());
}
return Text(courses.toString());
Run the app. Now instead of getting text to the console, you now have lots of text printed on the screen.