0

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, it work. But why we sometime need to put json.encode(data) sometime no need?
json.encode(data) parse your object to a string value, so when you have an object you have to use it to convert object into a string. When you have already a string value as json syntax, you don't need to parse it using json.encode
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.