将嵌套的 json 数组传递给 api flutter

Pass nested json array to api flutter

我有这个 json 格式需要传递给 api,它是一个嵌套的 json,我正在努力将它传递给 api,我尝试过以下方式,但它总是抛出格式错误

Json格式

{
   "id":116,
   "station_id":2,
   "branch_id":87,
   "manager_id":null,
   "employee_id":null,
   "vehicle_id":24,
   "customer_name":"SDSADSA",
   "mobile":"3213213213",
   "location":"SDSAD",
   "vehicle_model":null,
   "register_number":"ASDASD",
   "service_types":[
      1
   ],
   "accessories":[
      
   ],
   "suggestion":null,
   "inspection_comment":"SDSAD",
   "amount":"100.00",
   "extra_amount":"0.00",
   "discount":"0.00",
   "total_amount":"100.00",
   "feedback":null,
   "working_status_id":2,
   "remarks":null,
   "old_stock_details":[
      {
         "station_id":2,
         "branch_id":87,
         "branch_stock":{
            "id":14,
            "stock_id":4,
            "station_id":2,
            "branch_id":87,
            "kg":4,
            "gm":200,
            "ltr":0,
            "ml":0,
            "counter":0,
            "stock":{
               "id":4,
               "station_id":2,
               "name":"Wash Powder",
               "unit":1,
               "stock_date":"2021-12-10"
            }
         },
         "stock_id":4,
         "unit":1,
         "kg":1,
         "gm":100,
         "ltr":0,
         "ml":0,
         "counter":0
      }
   ],
   "new_stock_details":[
      {
         "station_id":2,
         "branch_id":87,
         "branch_stock":{
            "id":14,
            "stock_id":4,
            "station_id":2,
            "branch_id":87,
            "kg":4,
            "gm":200,
            "ltr":0,
            "ml":0,
            "counter":0,
            "stock":{
               "id":4,
               "station_id":2,
               "name":"Wash Powder",
               "unit":1,
               "stock_date":"2021-12-10"
            }
         },
         "stock_id":4,
         "unit":1,
         "kg":1,
         "gm":100,
         "ltr":0,
         "ml":0,
         "counter":0
      }
   ]
}

到目前为止我就是这样做的

 empData.then((data) async {
          var empId = data;
          stationData.then((data) async {
            var stationId = data;
            tokenData.then((datas) async {
              Branchdata.then((br_data) async {
              var token = datas;

              var branch_id=br_data;

              var data = {};
              var new_stock_details = [];
              var old_stock_details = [];
              var stocks = {};
              data["id"] = id;
              data["station_id"] = stationId;
              data["employee_id"] = selectedemp;
              data["branch_id"] = branch_id;
              data["manager_id"] = empId;
              data["customer_name"] = name;
              data["mobile"] = mobile;
              data["location"] = location;
              data["vehicle_id"] = vehicleId;
              data["register_number"] = registerNumber;
              data["service_types"] = serviceTypeId;
              data["accessories"] = accessoryId;
              data["working_status_id"] = workingStatusId;
              data["suggestion"] = suggesionbox;
              data["amount"] = amount;
              data["extra_amount"] = extraAmount;
              data["feedback"] = feedback;
              data["discount"] = discount;
              data["remarks"] = cancelRemark;
              data["role_id"] = roleId;
             
              for (int i = 0; i < list_add_old_stock_details.length; i++) {
                stocks = {};
                stocks["stock_id"] = list_add_old_stock_details[i].stock_id;
                stocks["branch_id"] = list_add_old_stock_details[i].branch_id;
                stocks["station_id"] = list_add_old_stock_details[i].station_id;
                stocks["kg"] = list_add_old_stock_details[i].kg;
                stocks["gm"] = list_add_old_stock_details[i].mg;
                stocks["ltr"] = list_add_old_stock_details[i].litre;
                stocks["ml"] =list_add_old_stock_details[i].mlil;
                stocks["counter"] = list_add_old_stock_details[i].count;
                new_stock_details.add(stocks);
              }
              data["old_stock_details"] = old_stock_details;

              for (int i = 0; i < list_add_stock_details.length; i++) {
                stocks = {};
                stocks["stock_id"] = list_add_stock_details[i].stock_id;
                stocks["branch_id"] = list_add_stock_details[i].branch_id;
                stocks["station_id"] = list_add_stock_details[i].station_id;
                stocks["kg"] = list_add_stock_details[i].kg;
                stocks["gm"] = list_add_stock_details[i].mg;
                stocks["ltr"] = list_add_stock_details[i].litre;
                stocks["ml"] = list_add_stock_details[i].mlil;
                stocks["counter"] = list_add_stock_details[i].count;
                new_stock_details.add(stocks);
              }
              data["new_stock_details"] = new_stock_details;

              jsonEncode(data);


              var response = await http.post(Uri.parse(Urls.VEHICLE_REGISTER),
                  headers: {
                    "Content-Type": "application/json",
                    'Authorization': 'Bearer $token'
                  },
                  body: jsonEncode(data));

              print('Response status: ${response.statusCode}');
              print('Response dashboard body: ${response.body}');
              Map<String, dynamic> value = json.decode(response.body);
              var success = value['success'];
              var message = value['message'];
              EasyLoading.dismiss();
              if (response.statusCode == 200) {
                if (success == true) {
                  EasyLoading.dismiss();
                  nameController.clear();
                  mobileController.clear();
                  locationController.clear();
                  registerController.clear();

                  CoolAlert.show(
                    context: context,
                    type: CoolAlertType.success,
                    text: message.toString(),
                    onConfirmBtnTap: () {
                      Navigator.of(context, rootNavigator: true).pop(true);
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => ListScreen(listType),
                        ),
                      );
                    },
                  );
                } else {
                  EasyLoading.dismiss();
                  final snackBar = SnackBar(content: Text(message));
                  ScaffoldMessenger.of(context).showSnackBar(snackBar);
                }
              } else {
                EasyLoading.dismiss();
                final snackBar = SnackBar(content: Text(message));
                ScaffoldMessenger.of(context).showSnackBar(snackBar);
              }
            });
            });
          });
        });

借助此插件,您可以生成 json 的结构模型,这样您就不必手动解析 json,避免某些键不匹配,因此它将 return null 并且不完成 json 的解析

尝试使用我之前提到的插件生成的这个class

class JsonExample {
  int id;
  int stationId;
  int branchId;
  dynamic managerId;
  dynamic employeeId;
  int vehicleId;
  String customerName;
  String mobile;
  String location;
  dynamic vehicleModel;
  String registerNumber;
  List<int> serviceTypes;
  List<dynamic> accessories;
  dynamic suggestion;
  String inspectionComment;
  String amount;
  String extraAmount;
  String discount;
  String totalAmount;
  dynamic feedback;
  int workingStatusId;
  dynamic remarks;
  List<OldStockDetails> oldStockDetails;
  List<NewStockDetails> newStockDetails;

  JsonExample({this.id, this.stationId, this.branchId, this.managerId, this.employeeId, this.vehicleId, this.customerName, this.mobile, this.location, this.vehicleModel, this.registerNumber, this.serviceTypes, this.accessories, this.suggestion, this.inspectionComment, this.amount, this.extraAmount, this.discount, this.totalAmount, this.feedback, this.workingStatusId, this.remarks, this.oldStockDetails, this.newStockDetails});

  JsonExample.fromJson(Map<String, dynamic> json) {
    if(json["id"] is int)
      this.id = json["id"];
    if(json["station_id"] is int)
      this.stationId = json["station_id"];
    if(json["branch_id"] is int)
      this.branchId = json["branch_id"];
    this.managerId = json["manager_id"];
    this.employeeId = json["employee_id"];
    if(json["vehicle_id"] is int)
      this.vehicleId = json["vehicle_id"];
    if(json["customer_name"] is String)
      this.customerName = json["customer_name"];
    if(json["mobile"] is String)
      this.mobile = json["mobile"];
    if(json["location"] is String)
      this.location = json["location"];
    this.vehicleModel = json["vehicle_model"];
    if(json["register_number"] is String)
      this.registerNumber = json["register_number"];
    if(json["service_types"] is List)
      this.serviceTypes = json["service_types"]==null ? null : List<int>.from(json["service_types"]);
    if(json["accessories"] is List)
      this.accessories = json["accessories"] ?? [];
    this.suggestion = json["suggestion"];
    if(json["inspection_comment"] is String)
      this.inspectionComment = json["inspection_comment"];
    if(json["amount"] is String)
      this.amount = json["amount"];
    if(json["extra_amount"] is String)
      this.extraAmount = json["extra_amount"];
    if(json["discount"] is String)
      this.discount = json["discount"];
    if(json["total_amount"] is String)
      this.totalAmount = json["total_amount"];
    this.feedback = json["feedback"];
    if(json["working_status_id"] is int)
      this.workingStatusId = json["working_status_id"];
    this.remarks = json["remarks"];
    if(json["old_stock_details"] is List)
      this.oldStockDetails = json["old_stock_details"]==null ? null : (json["old_stock_details"] as List).map((e)=>OldStockDetails.fromJson(e)).toList();
    if(json["new_stock_details"] is List)
      this.newStockDetails = json["new_stock_details"]==null ? null : (json["new_stock_details"] as List).map((e)=>NewStockDetails.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["id"] = this.id;
    data["station_id"] = this.stationId;
    data["branch_id"] = this.branchId;
    data["manager_id"] = this.managerId;
    data["employee_id"] = this.employeeId;
    data["vehicle_id"] = this.vehicleId;
    data["customer_name"] = this.customerName;
    data["mobile"] = this.mobile;
    data["location"] = this.location;
    data["vehicle_model"] = this.vehicleModel;
    data["register_number"] = this.registerNumber;
    if(this.serviceTypes != null)
      data["service_types"] = this.serviceTypes;
    if(this.accessories != null)
      data["accessories"] = this.accessories;
    data["suggestion"] = this.suggestion;
    data["inspection_comment"] = this.inspectionComment;
    data["amount"] = this.amount;
    data["extra_amount"] = this.extraAmount;
    data["discount"] = this.discount;
    data["total_amount"] = this.totalAmount;
    data["feedback"] = this.feedback;
    data["working_status_id"] = this.workingStatusId;
    data["remarks"] = this.remarks;
    if(this.oldStockDetails != null)
      data["old_stock_details"] = this.oldStockDetails.map((e)=>e.toJson()).toList();
    if(this.newStockDetails != null)
      data["new_stock_details"] = this.newStockDetails.map((e)=>e.toJson()).toList();
    return data;
  }
}

class NewStockDetails {
  int stationId;
  int branchId;
  BranchStock1 branchStock;
  int stockId;
  int unit;
  int kg;
  int gm;
  int ltr;
  int ml;
  int counter;

  NewStockDetails({this.stationId, this.branchId, this.branchStock, this.stockId, this.unit, this.kg, this.gm, this.ltr, this.ml, this.counter});

  NewStockDetails.fromJson(Map<String, dynamic> json) {
    if(json["station_id"] is int)
      this.stationId = json["station_id"];
    if(json["branch_id"] is int)
      this.branchId = json["branch_id"];
    if(json["branch_stock"] is Map)
      this.branchStock = json["branch_stock"] == null ? null : BranchStock1.fromJson(json["branch_stock"]);
    if(json["stock_id"] is int)
      this.stockId = json["stock_id"];
    if(json["unit"] is int)
      this.unit = json["unit"];
    if(json["kg"] is int)
      this.kg = json["kg"];
    if(json["gm"] is int)
      this.gm = json["gm"];
    if(json["ltr"] is int)
      this.ltr = json["ltr"];
    if(json["ml"] is int)
      this.ml = json["ml"];
    if(json["counter"] is int)
      this.counter = json["counter"];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["station_id"] = this.stationId;
    data["branch_id"] = this.branchId;
    if(this.branchStock != null)
      data["branch_stock"] = this.branchStock.toJson();
    data["stock_id"] = this.stockId;
    data["unit"] = this.unit;
    data["kg"] = this.kg;
    data["gm"] = this.gm;
    data["ltr"] = this.ltr;
    data["ml"] = this.ml;
    data["counter"] = this.counter;
    return data;
  }
}

class BranchStock1 {
  int id;
  int stockId;
  int stationId;
  int branchId;
  int kg;
  int gm;
  int ltr;
  int ml;
  int counter;
  Stock1 stock;

  BranchStock1({this.id, this.stockId, this.stationId, this.branchId, this.kg, this.gm, this.ltr, this.ml, this.counter, this.stock});

  BranchStock1.fromJson(Map<String, dynamic> json) {
    if(json["id"] is int)
      this.id = json["id"];
    if(json["stock_id"] is int)
      this.stockId = json["stock_id"];
    if(json["station_id"] is int)
      this.stationId = json["station_id"];
    if(json["branch_id"] is int)
      this.branchId = json["branch_id"];
    if(json["kg"] is int)
      this.kg = json["kg"];
    if(json["gm"] is int)
      this.gm = json["gm"];
    if(json["ltr"] is int)
      this.ltr = json["ltr"];
    if(json["ml"] is int)
      this.ml = json["ml"];
    if(json["counter"] is int)
      this.counter = json["counter"];
    if(json["stock"] is Map)
      this.stock = json["stock"] == null ? null : Stock1.fromJson(json["stock"]);
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["id"] = this.id;
    data["stock_id"] = this.stockId;
    data["station_id"] = this.stationId;
    data["branch_id"] = this.branchId;
    data["kg"] = this.kg;
    data["gm"] = this.gm;
    data["ltr"] = this.ltr;
    data["ml"] = this.ml;
    data["counter"] = this.counter;
    if(this.stock != null)
      data["stock"] = this.stock.toJson();
    return data;
  }
}

class Stock1 {
  int id;
  int stationId;
  String name;
  int unit;
  String stockDate;

  Stock1({this.id, this.stationId, this.name, this.unit, this.stockDate});

  Stock1.fromJson(Map<String, dynamic> json) {
    if(json["id"] is int)
      this.id = json["id"];
    if(json["station_id"] is int)
      this.stationId = json["station_id"];
    if(json["name"] is String)
      this.name = json["name"];
    if(json["unit"] is int)
      this.unit = json["unit"];
    if(json["stock_date"] is String)
      this.stockDate = json["stock_date"];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["id"] = this.id;
    data["station_id"] = this.stationId;
    data["name"] = this.name;
    data["unit"] = this.unit;
    data["stock_date"] = this.stockDate;
    return data;
  }
}

class OldStockDetails {
  int stationId;
  int branchId;
  BranchStock branchStock;
  int stockId;
  int unit;
  int kg;
  int gm;
  int ltr;
  int ml;
  int counter;

  OldStockDetails({this.stationId, this.branchId, this.branchStock, this.stockId, this.unit, this.kg, this.gm, this.ltr, this.ml, this.counter});

  OldStockDetails.fromJson(Map<String, dynamic> json) {
    if(json["station_id"] is int)
      this.stationId = json["station_id"];
    if(json["branch_id"] is int)
      this.branchId = json["branch_id"];
    if(json["branch_stock"] is Map)
      this.branchStock = json["branch_stock"] == null ? null : BranchStock.fromJson(json["branch_stock"]);
    if(json["stock_id"] is int)
      this.stockId = json["stock_id"];
    if(json["unit"] is int)
      this.unit = json["unit"];
    if(json["kg"] is int)
      this.kg = json["kg"];
    if(json["gm"] is int)
      this.gm = json["gm"];
    if(json["ltr"] is int)
      this.ltr = json["ltr"];
    if(json["ml"] is int)
      this.ml = json["ml"];
    if(json["counter"] is int)
      this.counter = json["counter"];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["station_id"] = this.stationId;
    data["branch_id"] = this.branchId;
    if(this.branchStock != null)
      data["branch_stock"] = this.branchStock.toJson();
    data["stock_id"] = this.stockId;
    data["unit"] = this.unit;
    data["kg"] = this.kg;
    data["gm"] = this.gm;
    data["ltr"] = this.ltr;
    data["ml"] = this.ml;
    data["counter"] = this.counter;
    return data;
  }
}

class BranchStock {
  int id;
  int stockId;
  int stationId;
  int branchId;
  int kg;
  int gm;
  int ltr;
  int ml;
  int counter;
  Stock stock;

  BranchStock({this.id, this.stockId, this.stationId, this.branchId, this.kg, this.gm, this.ltr, this.ml, this.counter, this.stock});

  BranchStock.fromJson(Map<String, dynamic> json) {
    if(json["id"] is int)
      this.id = json["id"];
    if(json["stock_id"] is int)
      this.stockId = json["stock_id"];
    if(json["station_id"] is int)
      this.stationId = json["station_id"];
    if(json["branch_id"] is int)
      this.branchId = json["branch_id"];
    if(json["kg"] is int)
      this.kg = json["kg"];
    if(json["gm"] is int)
      this.gm = json["gm"];
    if(json["ltr"] is int)
      this.ltr = json["ltr"];
    if(json["ml"] is int)
      this.ml = json["ml"];
    if(json["counter"] is int)
      this.counter = json["counter"];
    if(json["stock"] is Map)
      this.stock = json["stock"] == null ? null : Stock.fromJson(json["stock"]);
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["id"] = this.id;
    data["stock_id"] = this.stockId;
    data["station_id"] = this.stationId;
    data["branch_id"] = this.branchId;
    data["kg"] = this.kg;
    data["gm"] = this.gm;
    data["ltr"] = this.ltr;
    data["ml"] = this.ml;
    data["counter"] = this.counter;
    if(this.stock != null)
      data["stock"] = this.stock.toJson();
    return data;
  }
}

class Stock {
  int id;
  int stationId;
  String name;
  int unit;
  String stockDate;

  Stock({this.id, this.stationId, this.name, this.unit, this.stockDate});

  Stock.fromJson(Map<String, dynamic> json) {
    if(json["id"] is int)
      this.id = json["id"];
    if(json["station_id"] is int)
      this.stationId = json["station_id"];
    if(json["name"] is String)
      this.name = json["name"];
    if(json["unit"] is int)
      this.unit = json["unit"];
    if(json["stock_date"] is String)
      this.stockDate = json["stock_date"];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["id"] = this.id;
    data["station_id"] = this.stationId;
    data["name"] = this.name;
    data["unit"] = this.unit;
    data["stock_date"] = this.stockDate;
    return data;
  }
}

终于在@Elvis Salabarria Aqunio 的帮助下弄明白了,该模型非常有用,list_stock_details 通过添加新按钮增加,我已经制作了所需的模型

   empData.then((data) async {
      var empId = data;
      stationData.then((data) async {
        var stationId = data;
        tokenData.then((datas) async {
          Branchdata.then((br_data) async {
            var token = datas;
          
            var branch_id = br_data;
            EasyLoading.dismiss();

            List<NewStockDetails> listModel = [];
            List<OldStockDetails> old_listModel = [];

            for (int i = 0; i < list_stock_details.length; i++) {
              print(list_stock_details[i].unit);
              listModel.add(NewStockDetails(
                stationId: int.parse(stationId),
                branchId: int.parse(branch_id),
                stockId: int.parse(list_stock_details[i].stock_id),
                branchStock: BranchStock1(
                    id: int.parse(list_stock_details[i].id),
                    kg: int.parse(list_stock_details[i].kg),
                    gm: int.parse(list_stock_details[i].gm),
                    counter: int.parse(list_stock_details[i].count),
                    ml: int.parse(list_stock_details[i].mlil),
                    ltr: int.parse(list_stock_details[i].litre),
                    stock: Stock1(
                        id: int.parse(list_stock_details[i].id),
                        stationId: int.parse(stationId),
                        name: list_stock_details[i].stockname,
                        unit: list_stock_details[i].unit,
                        stockDate: "")),
                unit: list_stock_details[i].unit,
                kg: int.parse(list_stock_details[i].kg),
                gm: int.parse(list_stock_details[i].gm),
                counter: int.parse(list_stock_details[i].count),
                ml: int.parse(list_stock_details[i].mlil),
                ltr: int.parse(list_stock_details[i].litre),
              ));
            }
            AddStock addJson = new AddStock(
              id: int.parse(id),
              stationId: int.parse(stationId),
              branchId: int.parse(branch_id),
              vehicleId: int.parse(vehicleId),
              customerName: name,
              mobile: mobile,
              location: location,
              registerNumber: registerNumber,
              serviceTypes: serviceTypeId,
              accessories: accessoryId,
              suggestion: suggesionbox,
              amount: amount,
              extraAmount: extraAmount,
              feedback: feedback,
              discount: discount,
              totalAmount: totalAmount,
              remarks: cancelRemark,
              inspectionComment: "test",
              workingStatusId: int.parse(workingStatusId),
              newStockDetails: listModel,
              oldStockDetails: old_listModel,
            );

            var response = await 
            http.post(Uri.parse(Urls.VEHICLE_REGISTER),
                headers: {
                  "Content-Type": "application/json",
                  'Authorization': 'Bearer $token'
                },
                body: jsonEncode(addJson));

            print('Response status: ${response.statusCode}');
            print('Response dashboard body: ${response.body}');
            Map<String, dynamic> value = json.decode(response.body);
            var success = value['success'];
            var message = value['message'];
            EasyLoading.dismiss();
            if (response.statusCode == 200) {
              if (success == true) {
                EasyLoading.dismiss();
                nameController.clear();
                mobileController.clear();
                locationController.clear();
                registerController.clear();

                CoolAlert.show(
                  context: context,
                  type: CoolAlertType.success,
                  text: message.toString(),
                  onConfirmBtnTap: () {
                    Navigator.of(context, rootNavigator: true).pop(true);
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => ListScreen(listType),
                      ),
                    );
                  },
                );
              } else {
                EasyLoading.dismiss();
                final snackBar = SnackBar(content: Text(message));
                ScaffoldMessenger.of(context).showSnackBar(snackBar);
              }
            } else {
              EasyLoading.dismiss();
              final snackBar = SnackBar(content: Text(message));
              ScaffoldMessenger.of(context).showSnackBar(snackBar);
            }
          });
        });
      });
    });