Error: Expected a value of type ‘Iterable‘, but got one of type ‘\_JsonMap’

Issue

Have tried to create a List of objects out of a json file.

I get this error: Error: Expected a value of type ‘Iterable’, but got one of type ‘_JsonMap’

Future <List<Inspection>> FutureInspections() async {
    var inspections  <Inspection>[]; 
    final String response  await rootBundle.loadString('assets/sample.json');
      var inspectionsJson  json.decode(response); 
      for (var inspectionJson in inspectionsJson) {
        inspections.add(Inspection.fromJson(inspectionJson));
      }
    return inspections;
  }

[Update 03.11.2021 Inspection class]

class Inspection
{
  String _description"";
  int _interval0;
  int _state0;
  DateTime _datenew DateTime.now();

  Inspection(this._description, this._interval, this._state, this._date);

  Inspection.fromJson(Map<String, dynamic>json){
    _descriptionjson['description'];
    _intervaljson['interval'];
    _statejson['state'];
    _datejson['date'];
  }


  DateTime get date > _date;

  set date(DateTime value) {
    _date  value;
  }

  int get state > _state;

  set state(int value) {
    _state  value;
  }

  int get interval > _interval;

  set interval(int value) {
    _interval  value;
  }

  String get description > _description;

  set description(String value) {
    _description  value;
  }
}

the error pops up at this part of the code:

inspections.add(Inspection.fromJson(inspectionJson));

[Update 03.11.2021 Json-File] Json-File:

{
    "inspections": [
        {
            "date": "01.01.2021",
            "state": "1",
            "interval": "7",
            "description": "SampleText1"
        },
        {
            "date": "01.01.2021",
            "state": "2",
            "interval": "3",
            "description": "SampleText2"
        }
    ]
}

I don’t understand why. Can you please help me?

Solution

Response of json.decode is a _JsonMap. Out of it, extract the inspections as below.

Future<List<Inspection>> FutureInspections() async {
………

var inspectionsJson  json.decode(response);

final inspect  inspectionsJson['inspections'];   <———

for (var resp in inspect) {
  inspections.add(Inspection.fromJson(resp));
}
return inspections;
}

Also the json sample shown has String type for interval and state, String for date variable, but the Inspection class has int and DateTime types.This might need to change to String. After the values are put as String, they can be later converted to the desired type.

Answered By – ACR

Leave a Comment