Home > Back-end >  How to send list of model objects in json format to API in flutter
How to send list of model objects in json format to API in flutter

Time:12-13

I am working on a Food Delivery App in Flutter and I have a list of model objects in my cart System. I need to send this list to API in JSON format so I convert that to JSON before sending it to server but i am getting error:

errors: {: [Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Metronic.Models.FoodOrderInsert' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

I am beginner in Flutter and your kind response will highly be appreciated. I am currently converting list and sending it to API like this: I have my List of modelbjects:

List<FoodDetail> foodOrderDetails = [...]
var jsonObjectsList = [];
//Here I convert my list of FoodDetails into list of jsonObjects
for (var item in foodOrderDetail) {
  jsonObjectsList.add(item.toJson());
}
await http
    .post(
  Uri.parse(url),
  headers: ApiURLs.header,

  body: jsonEncode(jsonObjectsList)
)

And my API required data is:

[{
"OrderId": 0,
"ProductId": 0,
"Quantity": 0,
"Price": 0}]

my FoodDetail class contain same these properties and converted to json but the problem I think is in conveting whole list to json.

CodePudding user response:

i suggestion to use DIO lib its automatically convert your data to json check it: https://pub.dev/packages/dio

CodePudding user response:

use this class to parse the server response FoodExample foodExample=FoodExample.fromJson(jsonEncode(jsonObjectsList)) with this line you will have access to all the attributes of the class

class FoodExample {
  int orderId;
  int productId;
  int quantity;
  int price;

  FoodExample({this.orderId, this.productId, this.quantity, this.price});

  FoodExample.fromJson(Map<String, dynamic> json) {
    if(json["OrderId"] is int)
      this.orderId = json["OrderId"];
    if(json["ProductId"] is int)
      this.productId = json["ProductId"];
    if(json["Quantity"] is int)
      this.quantity = json["Quantity"];
    if(json["Price"] is int)
      this.price = json["Price"];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["OrderId"] = this.orderId;
    data["ProductId"] = this.productId;
    data["Quantity"] = this.quantity;
    data["Price"] = this.price;
    return data;
  }
}
  • Related