Home > Mobile >  Cast Complex JSON Dart
Cast Complex JSON Dart

Time:05-15

the dart code below allows you to decode a json that comes from a backend inside resultValue, I have the response of the rest call with the json shown below, when I go to create the list with the values I have the following error, to what is due? how do i fix it?

JSON Link

Error:

//Line:  return data.map((jsonObject) => new Manutenzione(

    flutter: Errore: type 'List<String>' 
is not a subtype of type 'String' in type cast

Dart code:

var urlmod = await Storage.leggi("URL")   "/services/rest/v3/processes/PreventiveMaint/instances";
    final resultValue = await apiRequest(Uri.parse(urlmod), {}, UrlRequest.GET, true);
    Map<String, dynamic> map = json.decode(resultValue);
    List<dynamic> data = map["data"];
    try {
      return data
          .map((jsonObject) => new Manutenzione(
                ["_id"] as String,
                ["_user"] as String,
                ["__user_description"] as String,
                ["Description"] as String,
                ["ShortDescr"] as String,
                ["_Site_description"] as String,
                ["_Team_description"] as String,
                ["_status_description"] as String,
                ["_Company_description"] as String,
              ))
          .toList();
    } catch (err) {
      print("Errore: "   err.toString());
    }
    return List.empty();
  }

JSON:

    {
       ...
        data: [
          {
            _id: value1,
            _user: value2,
            ..
          },
          {
            _id: value1,
            _user: value2,
            ..
          },

        ] 
    }

CodePudding user response:

You forgot to specify jsonObject before the square brackets.

var urlmod = await Storage.leggi("URL")   "/services/rest/v3/processes/PreventiveMaint/instances";
    final resultValue = await apiRequest(Uri.parse(urlmod), {}, UrlRequest.GET, true);
    Map<String, dynamic> map = json.decode(resultValue);
    List<dynamic> data = map["data"];
    try {
      return data
          .map((jsonObject) => new Manutenzione(
                jsonObject["_id"] as String,
                jsonObject["_user"] as String,
                jsonObject["__user_description"] as String,
                jsonObject["Description"] as String,
                jsonObject["ShortDescr"] as String,
                jsonObject["_Site_description"] as String,
                jsonObject["_Team_description"] as String,
                jsonObject["_status_description"] as String,
                jsonObject["_Company_description"] as String,
              ))
          .toList();
    } catch (err) {
      print("Errore: "   err.toString());
    }
    return List.empty();
  }
  • Related