How to pass a list of json to body of http request (post) in Flutter?

9,366

Solution 1

You can do it in a very simple way. Create payment.dart file and copy paste the below code classes.

class PaymentList {
PaymentList(this.payments);

List<Payment> payments;

Map<String, dynamic> toJson() => <String, dynamic>{
    'payment_slips': payments,
  };
}

class Payment {
Payment({this.name, this.personalId});

String name;
String personalId;

Map<String, dynamic> toJson() => <String, dynamic>{
    'personal_id': personalId,
    'name': name,
  };
}

Now you can covert it to the required json format using below code. For example I am creating a dummy list:

final PaymentList paymentList =
    PaymentList(List<Payment>.generate(2, (int index) {
  return Payment(name: 'Person $index', personalId: '$index');
}));
final String requestBody = json.encoder.convert(paymentList);

The requestBody variable will have the json string as follows:

  {"payment_slips": [
    {
        "personal_id": "0",
        "name": "Person 0"
    },
    {
        "personal_id": "1",
        "name": "Person 1"
    }
  ]}

Now you can call the api:

var response = await http.post(url, body: requestBody}

Note: Please import the below package, which will be required to access json:

import 'dart:convert';

Solution 2

So it looks like you are not getting the JSON you expect. I have put together some code to show you how to get the body you want.

Link to run in DartPad https://dartpad.dartlang.org/3fde03078e56efe13d31482dea8e5eef

    class PaymentSlipes {
      String name;
      String personaId;

      ObjPayment({this.name, this.personaId});

      //You create this to convert your object to JSON
      Map<String, dynamic> toJson() => {'name': name, 'personaId': personaId};
    }

    // This method is needed to convert the list of ObjPayment into an Json Array
    List encondeToJson(List<PaymentSlipes> list) {
      List jsonList = List();
      list.map((item) => jsonList.add(item.toJson())).toList();
      return jsonList;
    }

    // This is an example and this code will run in DartPad link above
    void main() {
      PaymentSlipes objPayment = PaymentSlipes(name: "Douglas", personaId: "123425465");
      PaymentSlipes objPayment2 = PaymentSlipes(name: "Dave", personaId: "123425465;
      PaymentSlipes objPayment3 = PaymentSlipes(name: "Mike", personaId: "123425465");
      var list = [objPayment, objPayment2, objPayment3];

      // This is the mapping of the list under the key payment_slips as per your example and the body i would pass to the POST
      var finalJson = {"payment_slips": encondeToJson(list)};
      print(finalJson);
    }
Share:
9,366
Dougsrodrigues
Author by

Dougsrodrigues

Updated on December 14, 2022

Comments

  • Dougsrodrigues
    Dougsrodrigues over 1 year

    I have objects that will filled by a user in a form. I parse these objects to json and add that json in a list to pass in body of request. But i cant do this.

      incrementListPaymentSlipes(PaymentSlipes objPayment) async {
        objPayment.name = "Douglas";
        objPayment.personalId = "00000000000";
        Map<String, dynamic> json = objPayment.toJson();
        listPaymentSlipes.add(jsonEncode(json));
      }
    
    var response = await http.post(url, body: {
    "payment_slips": listPaymentSlipes,
    }
    

    example of correct body:

    "payment_slips": [
        {      
          "personal_id": "01888728680",
          "name": "Fulano da Silva"
        }
      ]
    
     {"error":"'{{personal_id: 00000000000, name: Douglas}}' é invalido como 'payment_slips'","code":"payment_slips_invalid"}```