如何解析扑扑中的杰森地图列表? [英] How to parse List of maps Json in flutter?
本文介绍了如何解析扑扑中的杰森地图列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Json结构,其中包含三个地图,一个是然后列出产品总数和税额.我必须在颤抖中解析这个json结构.我在模型类上创建的.现在我在类型转换中遇到错误.
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'],
);
}
}
推荐答案
与其将products数组强制转换为列表,请尝试将其用作 Iterable
.
Instead of casting the products array to a list try using it as an Iterable
.
对我来说,以下代码有效(请注意, json.decode(String)
方法是从 dart:convert
包中导入的):
For me the following code works (note that the json.decode(String)
method is imported from the dart:convert
package):
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'],
);
}
}
这篇关于如何解析扑扑中的杰森地图列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文