Flutter How to create, for a rest api, nested json response class?

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

The json.decode method mentioned will convert a JSON string to Map<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 a fromJson 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 or dart: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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[
{
"word": "example",
"phonetics": [
{
"text": "/ɪɡˈzɑːmp(ə)l/",
"audio": "https://lex-audio.useremarkable.com/mp3/example_us.mp3"
}
],
"meanings": [
{
"partOfSpeech": "noun",
"definitions": [
{
"definition": "A thing characteristic of its kind or illustrating a general rule.",
"example": "this is a good example of bad behavior"
}
]
}
]
}
]
</code>
<code>[ { "word": "example", "phonetics": [ { "text": "/ɪɡˈzɑːmp(ə)l/", "audio": "https://lex-audio.useremarkable.com/mp3/example_us.mp3" } ], "meanings": [ { "partOfSpeech": "noun", "definitions": [ { "definition": "A thing characteristic of its kind or illustrating a general rule.", "example": "this is a good example of bad behavior" } ] } ] } ] </code>
[
  {
    "word": "example",
    "phonetics": [
      {
        "text": "/ɪɡˈzɑːmp(ə)l/",
        "audio": "https://lex-audio.useremarkable.com/mp3/example_us.mp3"
      }
    ],
    "meanings": [
      {
        "partOfSpeech": "noun",
        "definitions": [
          {
            "definition": "A thing characteristic of its kind or illustrating a general rule.",
            "example": "this is a good example of bad behavior"
          }
        ]
      }
    ]
  }
]

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class DictionaryEntry {
final String word;
final List<Phonetic> phonetics;
final List<Meaning> meanings;
DictionaryEntry({required this.word, required this.phonetics, required this.meanings});
factory DictionaryEntry.fromJson(Map<String, dynamic> json) {
return DictionaryEntry(
word: json['word'],
phonetics: (json['phonetics'] as List).map((e) => Phonetic.fromJson(e)).toList(),
meanings: (json['meanings'] as List).map((e) => Meaning.fromJson(e)).toList(),
);
}
}
class Phonetic {
final String text;
final String audio;
Phonetic({required this.text, required this.audio});
factory Phonetic.fromJson(Map<String, dynamic> json) {
return Phonetic(
text: json['text'],
audio: json['audio'],
);
}
}
class Meaning {
final String partOfSpeech;
final List<Definition> definitions;
Meaning({required this.partOfSpeech, required this.definitions});
factory Meaning.fromJson(Map<String, dynamic> json) {
return Meaning(
partOfSpeech: json['partOfSpeech'],
definitions: (json['definitions'] as List).map((e) => Definition.fromJson(e)).toList(),
);
}
}
class Definition {
final String definition;
final String example;
Definition({required this.definition, required this.example});
factory Definition.fromJson(Map<String, dynamic> json) {
return Definition(
definition: json['definition'],
example: json['example'] ?? '', // In case there is no example
);
}
}
</code>
<code>class DictionaryEntry { final String word; final List<Phonetic> phonetics; final List<Meaning> meanings; DictionaryEntry({required this.word, required this.phonetics, required this.meanings}); factory DictionaryEntry.fromJson(Map<String, dynamic> json) { return DictionaryEntry( word: json['word'], phonetics: (json['phonetics'] as List).map((e) => Phonetic.fromJson(e)).toList(), meanings: (json['meanings'] as List).map((e) => Meaning.fromJson(e)).toList(), ); } } class Phonetic { final String text; final String audio; Phonetic({required this.text, required this.audio}); factory Phonetic.fromJson(Map<String, dynamic> json) { return Phonetic( text: json['text'], audio: json['audio'], ); } } class Meaning { final String partOfSpeech; final List<Definition> definitions; Meaning({required this.partOfSpeech, required this.definitions}); factory Meaning.fromJson(Map<String, dynamic> json) { return Meaning( partOfSpeech: json['partOfSpeech'], definitions: (json['definitions'] as List).map((e) => Definition.fromJson(e)).toList(), ); } } class Definition { final String definition; final String example; Definition({required this.definition, required this.example}); factory Definition.fromJson(Map<String, dynamic> json) { return Definition( definition: json['definition'], example: json['example'] ?? '', // In case there is no example ); } } </code>
class DictionaryEntry {
  final String word;
  final List<Phonetic> phonetics;
  final List<Meaning> meanings;

  DictionaryEntry({required this.word, required this.phonetics, required this.meanings});

  factory DictionaryEntry.fromJson(Map<String, dynamic> json) {
    return DictionaryEntry(
      word: json['word'],
      phonetics: (json['phonetics'] as List).map((e) => Phonetic.fromJson(e)).toList(),
      meanings: (json['meanings'] as List).map((e) => Meaning.fromJson(e)).toList(),
    );
  }
}

class Phonetic {
  final String text;
  final String audio;

  Phonetic({required this.text, required this.audio});

  factory Phonetic.fromJson(Map<String, dynamic> json) {
    return Phonetic(
      text: json['text'],
      audio: json['audio'],
    );
  }
}

class Meaning {
  final String partOfSpeech;
  final List<Definition> definitions;

  Meaning({required this.partOfSpeech, required this.definitions});

  factory Meaning.fromJson(Map<String, dynamic> json) {
    return Meaning(
      partOfSpeech: json['partOfSpeech'],
      definitions: (json['definitions'] as List).map((e) => Definition.fromJson(e)).toList(),
    );
  }
}

class Definition {
  final String definition;
  final String example;

  Definition({required this.definition, required this.example});

  factory Definition.fromJson(Map<String, dynamic> json) {
    return Definition(
      definition: json['definition'],
      example: json['example'] ?? '', // In case there is no example
    );
  }
}

After you create above model classes, you can fetch and parse the API response like below.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import 'dart:convert';
import 'package:http/http.dart' as http;
Future<List<DictionaryEntry>> fetchWordData(String word) async {
final response = await http.get(Uri.parse('https://api.dictionaryapi.dev/api/v2/entries/en/$word'));
if (response.statusCode == 200) {
List<dynamic> jsonResponse = json.decode(response.body);
return jsonResponse.map((entry) => DictionaryEntry.fromJson(entry)).toList();
} else {
throw Exception('Failed to load word data');
}
}
</code>
<code>import 'dart:convert'; import 'package:http/http.dart' as http; Future<List<DictionaryEntry>> fetchWordData(String word) async { final response = await http.get(Uri.parse('https://api.dictionaryapi.dev/api/v2/entries/en/$word')); if (response.statusCode == 200) { List<dynamic> jsonResponse = json.decode(response.body); return jsonResponse.map((entry) => DictionaryEntry.fromJson(entry)).toList(); } else { throw Exception('Failed to load word data'); } } </code>
import 'dart:convert';
import 'package:http/http.dart' as http;

Future<List<DictionaryEntry>> fetchWordData(String word) async {
  final response = await http.get(Uri.parse('https://api.dictionaryapi.dev/api/v2/entries/en/$word'));

  if (response.statusCode == 200) {
    List<dynamic> jsonResponse = json.decode(response.body);
    return jsonResponse.map((entry) => DictionaryEntry.fromJson(entry)).toList();
  } else {
    throw Exception('Failed to load word data');
  }
}

Also If you dont care about creating models(not recommended) you can directly access the nested data using simple indexing with json['key'].

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://api.example.com/data'));
if (response.statusCode == 200) {
Map<String, dynamic> jsonData = json.decode(response.body);
// Accessing data directly from the JSON response
String name = jsonData['data1']['data2']['name'];
int age = jsonData['data1']['data2']['age'];
String city = jsonData['data1']['data2']['address']['city'];
String zipcode = jsonData['data1']['data2']['address']['zipcode'];
print('Name: $name');
print('Age: $age');
print('City: $city');
print('Zipcode: $zipcode');
} else {
throw Exception('Failed to load data');
}
}
</code>
<code>Future<void> fetchData() async { final response = await http.get(Uri.parse('https://api.example.com/data')); if (response.statusCode == 200) { Map<String, dynamic> jsonData = json.decode(response.body); // Accessing data directly from the JSON response String name = jsonData['data1']['data2']['name']; int age = jsonData['data1']['data2']['age']; String city = jsonData['data1']['data2']['address']['city']; String zipcode = jsonData['data1']['data2']['address']['zipcode']; print('Name: $name'); print('Age: $age'); print('City: $city'); print('Zipcode: $zipcode'); } else { throw Exception('Failed to load data'); } } </code>
Future<void> fetchData() async {
  final response = await http.get(Uri.parse('https://api.example.com/data'));

  if (response.statusCode == 200) {
    Map<String, dynamic> jsonData = json.decode(response.body);

    // Accessing data directly from the JSON response
    String name = jsonData['data1']['data2']['name'];
    int age = jsonData['data1']['data2']['age'];
    String city = jsonData['data1']['data2']['address']['city'];
    String zipcode = jsonData['data1']['data2']['address']['zipcode'];

    print('Name: $name');
    print('Age: $age');
    print('City: $city');
    print('Zipcode: $zipcode');
  } else {
    throw Exception('Failed to load data');
  }
}

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật