解析嵌套json失败flutter



我有这个json响应,它包含服务类型、车辆模型、附件、作为数组的工作状态,但我无法访问任何类,当我打印print(obj);时,它只显示空

Json文件

{
"success": true,
"message": "",
"data": {
"service_types": [
{
"id": 1,
"name": "Car Wash"
},
{
"id": 2,
"name": "Full Body Wash"
},
{
"id": 3,
"name": "Polishing"
},
{
"id": 4,
"name": "Engine Oil Checkup"
},

],
"vehicle_models": [
{
"id": 1,
"name": "SUV"
}
],
"accessories": [
{
"id": 2,
"name": "Mat Cover"
},
{
"id": 4,
"name": "Cash"
},
{
"id": 5,
"name": "Engine Room washing"
}
],
"working_statuses": [
{
"id": 0,
"name": "Registered"
},
{
"id": 1,
"name": "Work started"
},
{
"id": 2,
"name": "Work completed"
},
{
"id": 5,
"name": "Cancelled"
}
]
}
}

提取数据的代码

var response = await http.post(Uri.parse(Urls.DasboardData),
headers: {"Content-Type": "application/json"},
body: json.encode({
"vehicle_models": "",
"service_types": "",
"station_id":Station_id,
"accessories": "",
"working_statuses": "",
}));
Map<String, dynamic> value = json.decode(response.body);
var data = value['data'];
if (data.length > 0) {

for (int i = 0; i < data.length; i++) {
var obj = data[i];
print(obj);
var service_type_obj = obj['service_types'];
var vehicle_models_obj = obj['vehicle_models'];
var accessories_obj = obj['accessories'];
var working_statuses_obj = obj['working_statuses'];
DataList.add(GetAllModel(
service_type_obj['id'],
service_type_obj['name'],
vehicle_models_obj['id'],
vehicle_models_obj['name'],
accessories_obj['id'],
accessories_obj['name'],
working_statuses_obj['id'],
working_statuses_obj['name'],
));
}
setState(() {
print("UI UPDATED");
});
}
else
{
} 

型号

class GetAllModel {
String service_type_id,
service_type_name,
vehicle_models_id,
vehicle_models_name,
accessories_id,
accessories_name,
working_statuses_id,
working_statuses_name;

GetAllModel(
this.service_type_id,
this.service_type_name,
this.vehicle_models_id,
this.vehicle_models_name,
this.accessories_id,
this.accessories_name,
this.working_statuses_id,
this.working_statuses_name,
);
}

问题是在迭代信息时,数据大小是4,但它包含4个对象,因此您将无法访问data[i],因为data[i]不存在,如果它存在,data['service_types']是一个列表,如果您可以迭代它包含对象的信息。

因此,为了能够访问对象的信息,你必须像这样迭代它们:

for (var i = 0; i < data['service_types'].length; i++) {
print(data['service_types'][i]);
}

对于其他对象也是如此。

迭代的替代方案:

for (var item in data.values) {
print(item);
}

您需要更改这些:

var service_type_obj = obj['service_types'];
var vehicle_models_obj = obj['vehicle_models'];
var accessories_obj = obj['accessories'];
var working_statuses_obj = obj['working_statuses'];

进入这个:

var service_type_obj = obj['service_types'][0];
var vehicle_models_obj = obj['vehicle_models'][0];
var accessories_obj = obj['accessories'][0];
var working_statuses_obj = obj['working_statuses'][0];

您的对象位于列表中,要访问它们,必须使用索引,如[0]。

最新更新