Ameer HAmza
Ameer HAmza

Reputation: 1

I want to convert Object list to json array in flutter

I want to convert the a List<Object> to a List<List<dynamic>> and send it as JSON to an API.

Here is my Object model class CartMapModel:

class CartMapModel { 
  String itemName;
  String itemPrice;
  String itemDescription;
  
  CartMapModel({this.itemDescription,this.itemPrice,this.itemName});
  
  Map<String, dynamic> toJson() {
    return {
      "itemName": itemName,
      "itemPrice": itemPrice,
      "itemDescription" : itemDescription
    };
  }
}

Here is my List<CartMapModel>:

cartOrderList.add(
  CartMapModel(
    itemPrice: itmPrice.toString(),
    itemName: itmName,
    itemDescription: itmDesc,
  )
);

I want to convert it to a List<List<dynamic>>:

[
  [
    "Item Name 1",
    "123",
    "Item 1 Description"
  ],
  [
    "Item Name 2",
    "456",
    "Item 2 Description"
  ],
  [
    "Item Name 3",
    "789",
    "Item 3 Description"
  ]
]

Upvotes: 0

Views: 741

Answers (1)

Thierry
Thierry

Reputation: 8383

Is this what you are looking for?

List<Map<String, dynamic>> jsonDataList =
    cartOrderList.map((cartOrder) => cartOrder.toJson().values.toList()).toList();

Upvotes: 1

Related Questions