【问题标题】:post request complex json to api in flutter在颤振中将请求复杂的json发布到api
【发布时间】:2020-03-15 23:47:43
【问题描述】:

我有这个 json 我想发布到一个 api 但我不确定它是如何完成的..这就是请求的样子:

  {
    "products": [
        {"id":1, "qty": 1},{"id":2, "qty": 1}
    ],
    "vendor_id": 1,
    "notes": " ",
    "address": ""
}

这是我用来映射请求的请求类:

    class Order{

  int vendor_id;
  String address ,notes ;
  List<OrderProduct> products;

  Order({this.products , this.address , this.notes , this.vendor_id});

  Map<String, dynamic> toMap() {
    return {
      'vendor_id': vendor_id,
      'address': address,
      'notes': notes,
      'products': products,
    };
  }


}

class OrderProduct{
  int id , qty ;
  OrderProduct({this.id , this.qty});
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'qty': qty,
    };
  }
}

我错过了什么?

【问题讨论】:

    标签: json api dictionary flutter http-post


    【解决方案1】:

    就像json.encode(myArr)那样做, 例如

     Map<String, String> params = {
          "mobile": userNameController.text,
          "password": passwordController.text,
          "deviceid": '${fcmToken}',
        };
    
     Future<String> postRequest(var url, {var postParams}) async {
        return http
            .post(url, body: json.encode(postParams))// do json encoding here 
            .then((http.Response response) {
          final int statusCode = response.statusCode;
          print("postParams " + json.encode(postParams));
          print("statusCode " + '${statusCode} ${response.body}');
          if (statusCode < 200 || statusCode > 400 || json == null) {
            throw new Exception("Error while fetching data");
          }
          print(response.request);
          return response.body;
        });
      }
    

    【讨论】:

      【解决方案2】:

      我在正文中发布的 Json..

      {
             "products": [
                {"id":1, "qty": 1},{"id":2, "qty": 1}
             ],
             "vendor_id": 1,
             "notes": " ",
             "address": ""
          }
      

      您的 Post Api 调用如下:

      Future<Order> postOrder(int vendor_id, String notes, String address, int 
       id1,int q1, int id2, int q2) async {
      
       Paste your api url here
       String url = '';
       final response = await http.post(apiUrl, headers: {
         // Enter your headers parameter if needed
         //  E.g: 
        'Authorization' : 'xyz',
        'Content-Type' : 'application/json'
       },
      body: jsonEncode(<String, String>{
        'vendor_id' : vendor_id,
        'notes' : notes,
        'address' : address,
        'products' : [
         {'id': id1,'qty' : q1},
         {'id' : id2,'qty' : q2}
        ]
      }));
      
        if (response.statusCode == 200) {
          var data = jsonDecode(response.body.toString());
          print(data);
           return Order.fromJson(jsonDecode(response.body));
         } else {
        throw Exception('Failed to post user.');
        }
       }
      

      你的模型是这样的:

      class Order {
          List<Products>? products;
           int? vendorId;
           String? notes;
           String? address;
      
      Order({this.products, this.vendorId, this.notes, this.address});
      
      Order.fromJson(Map<String, dynamic> json) {
         if (json['products'] != null) {
           products = <Products>[];
           json['products'].forEach((v) {
             products!.add(new Products.fromJson(v));
           });
          }
          vendorId = json['vendor_id'];
          notes = json['notes'];
          address = json['address'];
        }
      
       Map<String, dynamic> toJson() {
         final Map<String, dynamic> data = new Map<String, dynamic>();
          if (this.products != null) {
            data['products'] = this.products!.map((v) => v.toJson()).toList();
          }
          data['vendor_id'] = this.vendorId;
          data['notes'] = this.notes;
          data['address'] = this.address;
          return data;
        }
       }
      
        class Products {
          int? id;
          int? qty;
      
          Products({this.id, this.qty});
      
          Products.fromJson(Map<String, dynamic> json) {
             id = json['id'];
             qty = json['qty'];
          }
       
           Map<String, dynamic> toJson() {
             final Map<String, dynamic> data = new Map<String, dynamic>();
                data['id'] = this.id;
                data['qty'] = this.qty;
                return data;
              }
           }
      

      【讨论】:

        猜你喜欢
        • 2019-12-19
        • 2020-11-06
        • 2022-01-27
        • 1970-01-01
        • 2020-07-23
        • 2021-08-11
        • 1970-01-01
        • 2021-07-12
        • 2019-09-06
        相关资源
        最近更新 更多