Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse List<dynamic> using json_serializable library in Flutter

Consider the following json:

[
 {
  "id": 1
  "name": "foo"
 },
 {
  "id": 1
  "name": "foo"
 }
]

I am trying to parse this using json_serializable library.

json.decode(response.body) returns List<dynamic>.

but the json_serializable auto-generates methods fromJson and toJson with type Map<String, dynamic json>.

is there any way in json_serializable to parse List<dynamic> with auto-generated methods and not manually?

like image 217
Akshar Patel Avatar asked May 25 '19 13:05

Akshar Patel


1 Answers

you should try it this way;

@JsonSerializable()
class Example{
    int id; String name;
    Example({this.id, this.name})
}

call your Future function and save it in a variable {parsed} and then convert your mapped data to list by doing this:

List<Example> result = parsed.map((i) => Example.fromJson(i)).toList();
like image 57
Adelodun Damilare Avatar answered Sep 27 '22 23:09

Adelodun Damilare