json - 以复杂对象为主体的 Dart HTTP Post
问题描述
Dart http 包的 post 方法只接受 String、List 或 Map 作为请求体。我需要将此列表作为正文发送
List item = widget.product
.map((prod) => {
"product_id": prod.id,
"product_name": prod.title,
"product_quantity": prod.quantity,
"product_reference": prod.reference
}).toList();
在邮递员中,我会将主体构建为原始 json
{"id_customer": "null",
"id_adresse": "null",
"id_carrier": "155",
"secure_key": "null",
"payment": "Paiement à la livraison",
"total_paid": "311.0",
"total_product": "298.0",
"total_shipping": "7.0",
"tax": "0.6",
"products": [{"product_id": "5444",
"product_name": "Batterie adaptable pour ordinateur portable Asus X550A 2200mAh",
"product_quantity": "1",
"product_reference": "null"},
{"product_id": "5433",
"product_name": "Batterie originale pour ordinateur portable Asus K52 4400mAh",
"product_quantity": "1",
"product_reference": "null"}]}
这是我的尝试
void addorders(String id , String id_adresse,String secure_key,String id_carrier,String paiement,double total,double total_product,double total_shipping,double tax, List products) async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key ) ?? 0;
String myUrl = "$serverUrl/orders";
final String prod=products.toString();
http.post(myUrl,
headers: {
'Accept':'application/json',
//"content-type": "application/json",
'Authorization' : 'JWT $value'
},
body: {
"id_customer":"$id",
"id_adresse":"$id_adresse",
"id_carrier":"$id_carrier",
"secure_key":"$secure_key",
"payment":"$paiement",
"total_paid":"$total",
"total_product":"$total_product",
"total_shipping":"$total_shipping",
"tax":"$tax",
"products":"$prod",
}).then((response){
// print('Response status : ${response.statusCode}');
print('Response body ');
print(response.request);
// print('Response body : ${id_carrier}');
}
);
}
我使用字符串编码 = json.encode(theMap) 但同样的问题我的 api 不读取列表产品请帮助。
解决方案
您应该使用转换器来获取对您的 json 数据进行数学运算并处理它的 dart 类,而不是像您那样传递您的值。
例如,您可以将此JSON 用于 Dart。您只需要从邮递员那里粘贴您的 json 数据即可恢复您的飞镖课程
在你只需要调用toJson()
你的类的方法来获取你的请求正文的 Map 之后
推荐阅读
- pine-script - 在 1 分钟图表上绘制 1d SMA 时的阶梯/块状分辨率
- grails - 在 Grails 应用程序中何时以及何时不需要控制器?
- android - 如何将 LiveData 实体转换为 LiveData 域模型
- node.js - 以快递方式将数据从一个文件发送到另一个文件
- node.js - 如何配置 apache 将 https 请求转发到在端口 1337 上运行的 Strapi/node 应用程序?
- javascript - 在 Joi 模式中添加 OR 以进行时间检查
- scala - scala 迭代器 hasNext 随机行为
- docker - Dockerize 并部署在 AKS 上具有 Kafka 使用者的 Spring 应用程序?
- solr - Solr 异常 java.lang.ClassNotFoundException: solr.DaitchMokotoffSoundexFilterFactory
- gcc - M1 MBP 上的 Clang 到 g++/GCC 链接