I have one Json structure with three maps, one is list of products then total and tax. I have to parse this json structure in flutter. I created on model class. Now i am getting the error in type casting.
怎么解决这个问题呢?
JSON 结构:
{
"products" : [
{
"cart_id": "7",
},
{
"cart_id": "7",
}
],
"total": 100,
"tax": 100
}
型号类别:
class CartModel {
List<Product> produtcts;
double total;
CartModel({this.produtcts, this.total});
factory CartModel.fromJson(Map<String, dynamic> json) {
var list = json['products'] as List;
print(list.runtimeType);
List<Product> products = list.map((i) =>
Product.fromJson(i)).toList();
return CartModel(
produtcts: products, total: json['total'],);
}
}
class Product {
String cartId;
Product({this.cartId,});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
productId: json['cart_id'],
);
}
}
不要将产品数组转换为列表,而是尝试将其用作Iterable
.
对我来说,以下代码有效(请注意json.decode(String)
方法是从导入的dart:convert
包裹):
var data = '{"products":[{"cart_id": "7"},{ "cart_id": "7"}], "total": 100, "tax": 100}';
var decoded = json.decode(data);
var cartModel = CartModel.fromJson(decoded);
class CartModel {
List<Product> produtcts;
int total;
CartModel({this.produtcts, this.total});
factory CartModel.fromJson(Map<String, dynamic> json) {
Iterable list = json['products'];
print(list.runtimeType);
List<Product> products = list.map((i) =>
Product.fromJson(i)).toList();
return CartModel(
produtcts: products, total: json['total'],);
}
}
class Product {
String productId;
Product({this.productId,});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
productId: json['cart_id'],
);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)