【问题标题】:how to post json array on flutter如何在颤振上发布json数组
【发布时间】:2020-06-26 13:59:46
【问题描述】:

我在用颤振发布 json 数组时遇到了一些问题。

当我使用 json 与邮递员打 api 时,它可以工作。截图邮递员:

因为我知道在 body 上只接受 Map String,String> CMIIW

所以我把身体变成了这样

List<Map<String,String>> products = [
  {
      "product_id": "1",
      "buy_quantity": "1",
      "product_price": "1000",
      "is_voucher": "0",
  },
  {
      "product_id": "2",
      "buy_quantity": "2",
      "product_price": "2000",
      "is_voucher": "0",
  },           
];

final String jsonProduct = json.encode(products);// here im trying to

Map<String,String> _body = {        
  "buyer_id": '',
  "buyer_firstname": postCart.buyerFirstname,
  "phone_number": postCart.phoneNumber,
  "transaction_total_price": postCart.transactionTotalPrice.toString(),
  "voucher_id": 0.toString(),
  "voucher_code": 0.toString(),
  "payment_id": postCart.paymentId.toString(),
  "payment_name": postCart.paymentName,  
  "products" : jsonProduct
};

但我仍然有错误,

谢谢!

【问题讨论】:

  • 抱歉我是新手问问题,抱歉图片无法显示,所以我在这里写关于邮递员的 json 帖子

标签: json flutter post


【解决方案1】:

如果要实现屏幕截图中的 JSON,则需要进行一些更改。

  1. 请注意,产品列表在转换为 JSON 时会显示不带引号的整数,因此需要在 Dart 类中将这些整数保存为 ints。 (也请注意首选语法。)
var products = <Map<String, int>>[
  {
    'product_id': 1,
    'buy_quantity': 1,
    'product_price': 1000,
    'is_voucher': 0,
  },
  {
    'product_id': 2,
    'buy_quantity': 2,
    'product_price': 2000,
    'is_voucher': 0,
  },
];
  1. _body 的类型需要更改,因为它现在包含一个列表和字符串。 (其余部分保持不变 - 就像 toStrings - 因为您的屏幕截图显示,即使是整数也被引用为字符串。)
var _body = <String, dynamic>{
  'buyer_id': '',
  'buyer_firstname': postCart.buyerFirstname,
  'phone_number': postCart.phoneNumber,
  'transaction_total_price': postCart.transactionTotalPrice.toString(),
  'voucher_id': 0.toString(),
  'voucher_code': 0.toString(),
  'payment_id': postCart.paymentId.toString(),
  'payment_name': postCart.paymentName,
  'products': products
};
  1. 最后 json 和(最好是)utf8 对生成的映射进行编码,并将其作为 http.post 的 body 参数传递。
var bytes = utf8.encode(json.encode(_body));
await http.post(url, body: bytes, headers: someHeaders);
  1. 您的一个标头可以是 content-type: application/json;encoding=utf-8,以告知服务器您正在发送 UTF8 编码的 JSON。

【讨论】:

    【解决方案2】:

    我假设您使用的是http package。

    这是一个如何使用正文上的 json 有效负载发出 HTTP POST 请求的示例:

    Future<Lead> createLead(String clientName, String clientEmail, String clientPhone, String eventId) async {
    
      // Create storage
      final storage = new FlutterSecureStorage();
    
      // Get API url from env
      String url = (DotEnv().env['BASE_URL'] + "/leads/create");
      String authToken = await storage.read(key: 'api-token');
    
      // Create some request headers
      Map<String, String> requestHeaders = {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          'X-Token': authToken
        };
    
    
      final response = await http.post(
        url,
        // enconde some JSON data on the request body
        body: json.encode(
          {
            'event_id': eventId,
            'name': clientName,
            'phone': clientPhone,
            'email': clientEmail
          }
        ),
        headers: requestHeaders
      );
    
      if (response.statusCode == 200) {
        final leadsJson = json.decode(response.body);
        Lead lead = Lead.fromJson(leadsJson);
        return lead;
      } else {
        // If that response was not OK, throw an error.
        // throw Exception('Failed to load post');
        return null;
      }
    }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2021-01-26
      • 2022-01-27
      • 2020-04-22
      • 2021-03-17
      • 2018-08-09
      • 2019-12-19
      • 2021-03-21
      • 2019-12-12
      相关资源
      最近更新 更多