我想使用flutterwith將包含另一個 json 資料的 json 資料發布到 API 中http
這是我要發送的資料示例
{sales_representative: 1,
doctor: 1,
remark: My Remark,
date: 2021-12-05,
medicines: [
{medicine: 1,
quantity_type: Tablet,
quantity: 55
},
{medicine: 1,
quantity_type: Tablet,
quantity: 5
}
]
}
這是我的 API 方法
static Future postSale(body) {
return http.post(Uri.parse('http://192.168.56.1:8000/api/sales/'),
body: body);
}
但是顫振給了我這個錯誤:
Unhandled Exception: type 'List<Map<String, dynamic>>' is not a subtype of type 'String' in type cast
uj5u.com熱心網友回復:
我發現我的問題是什么:
- 我沒有用 包裹身體
jsonEncode。 - 我沒有指定標題。
這就是我所做的讓它發揮作用。
return http.post(Uri.parse('http://192.168.56.1:8000/api/sales/'),
headers: {
'Content-Type': 'application/json',
},
body: jsonEncode(body));
}
uj5u.com熱心網友回復:
請這樣做。
var data ={};
var medicines = [];
var medicineData ={};
data["sales_representative"] = 1;
data["doctor"] =1;
data["remark"]="my remarks";
data["date"] = "2021-12-05";
for(int i=0;i<2; i )
{
medicineData ={};
medicineData["medicine"] =1;
medicineData["quantity_type"] = "Tablet";
medicineData["quantity"] =5;
medicines.add(medicineData);
}
data["medicines"] = medicines;
并像這樣傳遞給這個 api 請求
http.post(Uri.parse('apiUrl'),
headers: {
'Content-Type': 'application/json',
},
body: jsonEncode(data));
}
以下是輸出 json.encode(data)
{
"sales_representative": 1,
"doctor": 1,
"remark": "my remarks",
"date": "2021-12-05",
"medicines": [
{
"medicine": 1,
"quantity_type": "Tablet",
"quantity": 5
},
{
"medicine": 1,
"quantity_type": "Tablet",
"quantity": 5
}
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/374718.html
上一篇:Flutter:json_serializable型別'_InternalLinkedHashMap<Object?,Object?>'不是型別'Map<
