我想将数据发送到我的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);
现在我对无效参数有一个错误,因为我不知道如何发送JSON数组。
有人可以帮助我吗?
答案 0 :(得分:1)
body参数应为Map。由于您将json数据存储在var(字符串)中,因此需要将其转换为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);
答案 1 :(得分:1)
您的数据字符串不遵循JSON语法。
JSON语法为:
例如:
var
您应该以这种方式编写字符串,或者也可以创建一个对象,然后使用var data = '{ "requests": [{"OptionID": [{ "ID": "A1"} ],"content": {"img": "image" }}]}';
创建正确的字符串。
例如:
json.encode(data)