Tanjim ahmed
Tanjim ahmed

Reputation: 599

Convert Json of maps to list<Object> in flutter

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?

Upvotes: 2

Views: 2921

Answers (1)

eamirho3ein
eamirho3ein

Reputation: 17900

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();

Upvotes: 2

Related Questions