flutter - 如何在 Flutter 中发布 JSON 数组
问题描述
我想将数据发送到我的 API URL。如何在 JSON 数组下方发布?
我要发送的数据是这样的:
requests: [
{
OptionID: [
{
ID: 'A1'
}
],
content: {
img: 'image'
}
}
]
这是我的代码:
var data = "requests: [{ OptionID: [ {ID: 'A1'}], content: { img: 'image'}}]";
http.Response response = await http.post("https://MY_API_URL", body: data);
print(response.body);
现在我有一个关于 Invalid Argument 的错误,因为我不知道如何发送 JSON 数组。
谁能帮我?
解决方案
body 参数应该是一个 Map。由于您将 json 数据保存在 var (String) 中,因此需要将其转换为 Map。你可以这样做:
//you'll need jsonEncode and that is part of dart:convert
import 'dart:convert';
//Since you have data inside of "" it is a String. If you defined this as a Map<String, dynamic> and created this as a map, you wont need to convert.
var data = "requests: [{ OptionID: [ {ID: 'A1'}], content: { img: 'image'}}]";
//use jsonEncode with your data here
http.Response response = await http.post("https://MY_API_URL", body: jsonEncode(data));
print(response.body);
推荐阅读
- python - 一个一个地读取多个文件,并根据每个文件的不同变量提取内容
- linux - systemd 在clock_gettime 中止
- c++ - 如果其中一个方法在子类中有重写,C++ 有没有办法强制重写一组方法?
- mysql - MySQL:使用别名定义 CONCAT 的数据类型
- python - 根据列表中元素的数量过滤嵌套字典
- android - afterTextChanged 切换设备方向时自动触发
- javascript - 我想多次打印数组值
- angular - 在表单更改并且在 Angualr 和 RxJS 中出现延迟后立即执行某项操作的正确方法是什么?
- javascript - 为什么 switch case 中的逻辑 OR 运算符会表现得很奇怪?
- windows - 尝试启动进程时出现powershell错误