【问题标题】:Error: Expected a value of type 'Iterable<dynamic>', but got one of type '_JsonMap'错误:需要一个“Iterable<dynamic>”类型的值,但得到一个“_JsonMap”类型的值
【发布时间】:2021-12-17 08:20:31
【问题描述】:

已尝试从 json 文件中创建对象列表。

我收到此错误:错误:需要一个“Iterable”类型的值,但得到一个“_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;
  }

[更新 03.11.2021 检查类]

class Inspection
{
  String _description="";
  int _interval=0;
  int _state=0;
  DateTime _date=new DateTime.now();

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

  Inspection.fromJson(Map<String, dynamic>json){
    _description=json['description'];
    _interval=json['interval'];
    _state=json['state'];
    _date=json['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;
  }
}

这部分代码弹出错误:

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

[更新 03.11.2021 Json-File] Json 文件:

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

我不明白为什么。你能帮帮我吗?

【问题讨论】:

  • 您能否包括assets/sample.json 的外观以及Inspection 类的其余部分?

标签: json flutter dart


【解决方案1】:

json.decode 的响应是一个_JsonMap。从中提取如下检查。

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;
}

显示的 json 示例还具有用于间隔和状态的字符串类型,用于日期变量的字符串,但检查类具有 int 和 DateTime 类型。这可能需要更改为字符串。将值作为字符串放入后,可以稍后将它们转换为所需的类型。

【讨论】:

    猜你喜欢
    • 2021-07-13
    • 2021-10-23
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2021-06-12
    • 2022-01-08
    相关资源
    最近更新 更多