Home > OS >  Convert Json of maps to list<Object> in flutter
Convert Json of maps to list<Object> in flutter

Time:10-13

I have a JSON like that

 [  
    {
        "id": "2a5",
        "employeeNumber": "101",
        "firstName": "Sachin",
        "lastName": "Agrawal"
    },
    {
        "id": "1f7",
        "employeeNumber": "151",
        "firstName": "Karsten",
        "lastName": "Andersen"
    },
]

I tried to parse the JSON like that

List<Employee> employees = (jsonDecode(response.data) as List)
          .map((data) => Employee.fromJson(data))
          .toList();

it causes the following error

List<dynamic>' is not a subtype of type 'String'

when I try to decode the JSON it causes the following error

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'String' 

what is the proper way to parse this type of JSON?

CodePudding user response:

You don't need to decode your response.data, it is already in list form. So instead of this:

List<Employee> employees = (jsonDecode(response.data) as List)
          .map((data) => Employee.fromJson(data))
          .toList();

try this:

List<Employee> employees = (response.data as List)
          .map((data) => Employee.fromJson(data))
          .toList();
  • Related