How to parse List of maps Json in flutter?

Viewed 13054

enter image description hereenter image description hereenter image description hereI 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.

How to solve this?

JSON Structure:

{
  "products" : [
     {                  
       "cart_id": "7",      
     },          
     {                  
       "cart_id": "7",
     }     
  ],
  "total": 100,
  "tax": 100
}

Model class :

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'],
        );
    }
}
2 Answers

Instead of casting the products array to a list try using it as an Iterable.

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'],
        );
    }
}

Quite simply :

 List<CartModel> list = new List();
  var jsonlist = jsonDecode(yourJsonString) as List;
  jsonlist.forEach((e) {
    list.add(CartModel.fromJson(e));
  });
Related