[英]In HTTP post request, How to pass JSON array having multiple Object in URL query
[英]How to post json object from array in http post request flutter?
我正在做測驗我已將問題 id 和選項 id 保存在數組中,現在我必須在 json object 中的 http 發布方法中發布這些數據。 我不知道如何將數組轉換為 json object 這是我的 http.post 方法。
submit(testId,List<String> answer) async {
try {
Response response = await post(
Uri.parse(NetworkConstants.BASE_URL + 'get-participate-to-test/${widget.id}'),
headers: {
"Authorization": "Bearer $token"
},
body:json.encode(
{
'test_id': testId,
'question': answer,
}
));
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data);
showToast(context, data['message']);
// Navigator.of(context).pushAndRemoveUntil(
// MaterialPageRoute(builder: (context) => HomeScreen()),
// (Route<dynamic> route) => false);
} else {
var data = jsonDecode(response.body.toString());
print(data);
showToast(context, data['message']);
}
} catch (e) {
setState(() {
print(e);
});
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Exception:"),
content: Text(e.toString()),
actions: [
TextButton(
child: Text("Try Again"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
}
} 這里我發送變量(答案)作為列表[{question_id: 2, option_id: 14}]
如何將其轉換為 json 編碼 object 並發布在方法的正文中?
這里的答案是 Map<String, int> 的列表。 您已經通過在正文中使用 json.encode 將其轉換為 json。
submit(testId,List<Map, String> answer) async {
try {
Response response = await post(
Uri.parse(NetworkConstants.BASE_URL + 'get-participate-to-test/${widget.id}'),
headers: {
"Authorization": "Bearer $token"
},
body:json.encode(
{
'test_id': testId,
'question': answer,
}
));
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data);
showToast(context, data['message']);
// Navigator.of(context).pushAndRemoveUntil(
// MaterialPageRoute(builder: (context) => HomeScreen()),
// (Route<dynamic> route) => false);
} else {
var data = jsonDecode(response.body.toString());
print(data);
showToast(context, data['message']);
}
} catch (e) {
setState(() {
print(e);
});
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Exception:"),
content: Text(e.toString()),
actions: [
TextButton(
child: Text("Try Again"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.