【问题标题】:Flutter - sending complex JSON to serverFlutter - 将复杂的 JSON 发送到服务器
【发布时间】:2019-11-22 20:56:27
【问题描述】:

我正在开发一个关于颤振的购物应用程序,我必须将用户信息与购物车中的商品列表一起发送到服务器。我整天在互联网上搜索,找不到适合我的解决方案。我必须提交的 JSON 如下所示。

{
"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)"
 }]
}

我向服务器发送数据的方式如下。

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

我收到的异常是 “未处理的异常:将对象转换为可编码对象失败:'CartItem' 的实例”

CartItem 类看起来像这样

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

请帮我解决这个问题。谢谢

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    您正在尝试对包含对象的列表进行编码。当在一个对象上调用 encode 时,它​​会尝试调用方法toJson()。如果这个方法没有实现,json.encode会失败。

    尝试将此添加到您的 CartItem 课程中:

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

    你也拼错了defaultCategory,所以我在defalutCategory的回答中更改了它

    【讨论】:

    • 我正在尝试,但我应该在哪里调用这个方法?
    猜你喜欢
    • 2018-10-31
    • 1970-01-01
    • 2020-11-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    相关资源
    最近更新 更多