qing
qing

Reputation: 885

How to post JSON array in Flutter

I want to send data to my API URL. How to post below JSON array?

The data I want to send is this:

  requests: [
            {
                OptionID: [
                {
                    ID: 'A1'
                }
                ],
                content: {
                img: 'image'
                }
            }
            ]

Here is my code:

var data = "requests: [{ OptionID: [ {ID: 'A1'}], content: { img: 'image'}}]";
http.Response response = await http.post("https://MY_API_URL", body: data);
print(response.body);

Now I have an error about Invalid Argument because I don't know how to send a JSON array.

Can anyone help me?

Upvotes: 0

Views: 3847

Answers (2)

SaltH2OFish
SaltH2OFish

Reputation: 220

The body parameter should be a Map. Since you have your json data in a var (String) it needs to be converted to a Map. You can do this:

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

Upvotes: 1

mraf4
mraf4

Reputation: 106

Your data string does not follow a JSON syntax.

JSON syntax is:

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays
  • field name must be in double quotes

For example:

var data = '{ "requests": [{"OptionID": [{ "ID": "A1"} ],"content": {"img": "image" }}]}';

You should compose your string in this way or you can create an object as well and then using json.encode(data) for creating the right string.

For example:

var data = {
     "requests": [
    {
        "OptionID": [
          {
            "ID": "A1"
          }
        ],
        "content": {
          "img": "image"
        }
    }
    ]
}

json.encode(data)

Upvotes: 1

Related Questions