嘗試從 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));
[2021 年 11 月 3 日更新 Json 檔案] Json 檔案:
{
"inspections": [
{
"date": "01.01.2021",
"state": "1",
"interval": "7",
"description": "SampleText1"
},
{
"date": "01.01.2021",
"state": "2",
"interval": "3",
"description": "SampleText2"
}
]
}
我不明白為什么。你能幫我么?
uj5u.com熱心網友回復:
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 示例具有用于間隔和狀態的 String 型別,用于日期變數的 String 型別,但檢查類具有 int 和 DateTime 型別。這可能需要更改為 String。將值作為字串放入后,可以稍后將它們轉換為所需的型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346602.html
下一篇:MongoDB在陣列中創建陣列
