error when trying to decode json and casting it

Issue

I am trying to decode complex json data and always resulting in error.
Below are my json data:

    {
    "status_code": 200,
    "message": "Successfully get data user",
    "data": {
        "sec_user": {
            "clientIp": "1.4.2.54",
            "officeid": "N/A",
        },
        "username": "uname",
        "name1": "",
        "menus": [
            {
                "appl_id": "MTC",
                "menu_caption": "Master",
                "menu_path": "/master",
                "submenus": [
                    {
                        "menu_caption": "Machine List",
                        "note1": "master",
                        "sub_menu_id": "1",
                        "route_path": "/machine_list"
                    },
                    {
                        "menu_caption": "Sparepart Category",
                        "note1": "master",
                        "sub_menu_id": "1",
                        "route_path": "/sparepart_category"
                    }
                ]
            },
            {
                "appl_id": "MTC",
                "menu_caption": "Master",
                "menu_path": "/master",
                "submenus": [
                    {
                        "menu_caption": "Machine List",
                        "note1": "master",
                        "sub_menu_id": "1",
                        "route_path": "/machine_list"
                    }
                ]
            },
        ]
    }
}

and I already create a model class using json to dart (and already retouch it a bit) and use json annotation and build runner. Then I get an error everytime I tried to decode the body of this json

if (jsonResponse.statusCode == 200) {
  final jsonItems =
      json.decode(jsonResponse.body).cast<Map<String, dynamic>>();
  List<Profile> profile = jsonItems.map<Profile>((json) {
    return MyMenu.fromJson(json);
  }).toList();
  return profile;
}

I always get this error message (attached on the image bellow):
enter image description here

What when wrong with my code ?

Solution

End up answering my question, I did this:

json.decode(jsonResponse.body)['data']['menus'].cast<Map<String, dynamic>>();

Don’t know if there is any other perfect method to do this.

Answered By – user3931627

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published