首页 > 解决方案 > 如何在 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 数组。

谁能帮我?

标签: flutterdart

解决方案


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);

推荐阅读