Using Flutter, I would like to read a nested rest api.
I found this free rest api here: https://dictionaryapi.dev/
But I don’t understand how to create a class for a nested json response. I’ve read that I don’t actually need to create a class, but rather use a package to process the json response. T/F?
Could you please outline how to construct a class for the above example.
2
Answers
The
json.decode
method mentioned will convert a JSON string toMap<String, dynamic>
(or a list depending on data shape). However if the data is deeply nested it will probably be preferable to create a class and either manually unpack the data in afromJson
constructor or use the JsonSerializable package to generate that method for you.Manual approach: https://medium.com/@raphaelrat_62823/consuming-rest-api-in-flutter-a-guide-for-developers-2460d90320aa
Generated approach: https://pub.dev/packages/json_serializable
You are right, there are packages like
json_serializable
ordart:convert
that help parse JSON, but to maintain good maintainability and type safety, it is a good practice to make model classes for nested JSON responses at least in complex apps.Checkout below API response.
It has a nested structure containing lists of objects (like phonetics and meanings). Lets try out the manual approach(if you need generated approach learn
freezed
package) to explain your scope.As the first step You need to create classes to represent this structure. Checkout the below example.
After you create above model classes, you can fetch and parse the API response like below.
Also If you dont care about creating models(not recommended) you can directly access the nested data using simple indexing with
json['key']
.