Aamir Shaikh
Aamir Shaikh

Reputation: 47

Flutter - sending complex JSON to server

I am developing a shopping App on flutter where I have to send user info along with the list of items in cart to server. I searched over internet all the day and couldn't find solution that works for me. JSON that I have to submit, looks like the following.

{
"areaId": 9,
"userId": 4,
"totalOrder": [{
    "categoryId": "1",
    "itemId": "1",
    "priceOfItem": 28,
    "serviceTypeId": 1,
    "title": "Shalwar Kameez"
}, {
    "categoryId": "1",
    "itemId": "2",
    "priceOfItem": 28,
    "serviceTypeId": 1,
    "title": "Shalwar Kameez Ladies (2Pcs)"
}, {
    "categoryId": "1",
    "itemId": "2",
    "priceOfItem": 28,
    "serviceTypeId": 1,
    "title": "Shalwar Kameez Ladies (2Pcs)"
 }]
}

The way I am sending data to server is following.

 Future<String> saveOrder() async {
   var map = new Map<String, dynamic>();

   map["userId"] = await SharedPreferencesUser.getUserId();
   map["areaId"] = await SharedPreferencesUser.getAreaId();
   map["totalOrder"] = cart.items; // this is list of items in cart List<CartItem> 

   var res = await http.post(
   Uri.encodeFull(Url.url + Apis.saveOrder),
   headers: {"Accept": "application/json"},
   body: json.encode(map), //encoding to json
   );

  return res.body;
}

The Exception I am receiving is "Unhandled Exception: Converting object to an encodable object failed: Instance of 'CartItem'"

CartItem class looks like this

class CartItem {
  String id;
  String categoryId;
  String itemName;
  int piece;
  int price;
  int quantity;
  String serviceType;
  String serviceId;
  String defalutCategory;

  CartItem(this.id, this.categoryId, this.itemName, this.piece, this.price,
      this.quantity, {this.serviceType, this.serviceId, this.defalutCategory});
}

Kindly help me sorting this problem. Thanks

Upvotes: 1

Views: 603

Answers (1)

WhimsicalPyro
WhimsicalPyro

Reputation: 46

You are trying to encode a List which contains an object. When encode is called on an object, it will try calling the method toJson(). If this method is not implemented, json.encode will fail.

Try adding this to your CartItem class:

Map<String, dynamic> toJson() =>  {
    'id': id,
    'categoryId': categoryId,
    'itemName': itemName,
    'piece': piece,
    'price': price,
    'quantity': quantity,
    'serviceType': serviceType,
    'serviceId': serviceId,
    'defaultCategory': defaultCategory,
  };

also you spelled defaultCategory wrong so I changed it in my answer from defalutCategory

Upvotes: 2

Related Questions