Parsing JSON that has a nested array of objects in Dart? Parsing JSON that has a nested array of objects in Dart? dart dart

Parsing JSON that has a nested array of objects in Dart?


Try genres = (jsonMap['genres'] as List).map((i) => Genre.fromJson(i)).toList()

The issue: calling map without the cast makes it a dynamic call, which means the return type from Genre.fromJson is also dynamic (not Genre).

Take a look at https://flutter.io/json/ for some hints.

There are solutions, like https://pub.dartlang.org/packages/json_serializable, that makes this much easier


Here is an example that is simple and easy to understand.

With the JSON string as a nested object like this.

{  "title": "Dart Tutorial",  "description": "Way to parse Json",  "author": {    "name": "bezkoder",    "age": 30  

}}There are 2 classes we can think about:

  • User for author
  • Tutorial for {title, description, author}

So we can define a new Tutorial like this.

class User {  String name;  int age;  ...}class Tutorial {  String title;  String description;  User author;  Tutorial(this.title, this.description, this.author);  factory Tutorial.fromJson(dynamic json) {    return Tutorial(json['title'] as String, json['description'] as String, User.fromJson(json['author']));  }  @override  String toString() {    return '{ ${this.title}, ${this.description}, ${this.author} }';  }}

The main() function now looks like the following code.import 'dart:convert';

main() {  String nestedObjText =      '{"title": "Dart Tutorial", "description": "Way to parse Json", "author": {"name": "bezkoder", "age": 30}}';  Tutorial tutorial = Tutorial.fromJson(jsonDecode(nestedObjText));  print(tutorial);

Check the result, you can see our nested object:

{ Dart Tutorial, Way to parse Json, { bezkoder, 30 } }

See that :Dart/Flutter parse JSON string into Nested Object