我在用flutter发布json数组时遇到一些问题。
当我使用json与邮递员联系api时,它可以工作。屏幕截图邮递员:
由于我知道身体上只接受Map << strong> 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
};
但我仍然出错,
谢谢!
答案 0 :(得分:0)
我假设您正在使用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;
}
}
希望有帮助。
答案 1 :(得分:0)
如果要在屏幕快照中实现JSON,则需要进行一些更改。
int
。 (也请注意首选语法。)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,
},
];
_body
的类型需要更改,因为它现在包含列表和字符串。 (其余部分都保持不变-像toString
一样,如屏幕截图所示,即使整数也被引用为字符串。)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
};
body
的{{1}}参数传递。http.post
var bytes = utf8.encode(json.encode(_body));
await http.post(url, body: bytes, headers: someHeaders);
,以告诉服务器您正在发送UTF8编码的JSON。