如何在扑扑中解析地图列表Json?

时间:2019-06-26 10:44:37

标签: json flutter

enter image description here enter image description here enter image description here我有一个具有三个地图的Json结构,一个是产品列表,然后是总计和税额。我必须在颤抖中解析这个json结构。我在模型类上创建的。现在我在类型转换中遇到错误。

如何解决这个问题?

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

3 个答案:

答案 0 :(得分:0)

与其将products数组强制转换为列表,请尝试将其用作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'],
        );
    }
}

答案 1 :(得分:0)

  
    

如何解决这个问题?

  

您可以通过这种方式(通过使用JSON数据模型)解决它。

import 'dart:convert';

import 'json_objects.dart';

main(List<String> args) {
  var json = jsonDecode(body) as Map<String, dynamic>;
  var shoppingCart = ShoppingCart.fromJson(json);
  var products = shoppingCart.products;
  for (var product in products) {
    print('${product.cartId}');
  }
}

var body = '''
{
  "products": [
    {
      "cart_id": "7"
    },
    {
      "cart_id": "7"
    }
  ],
  "total": 100,
  "tax": 100
}''';

结果:

7
7

使用的数据模型。

class Product {
  final String apiId;
  final String cartId;
  final String cartQuantity;
  final String customerId;
  final String recurringId;

  Product(
      {this.apiId,
      this.cartId,
      this.cartQuantity,
      this.customerId,
      this.recurringId});

  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      apiId: json['api_id'] as String,
      cartId: json['cart_id'] as String,
      cartQuantity: json['cart_quantity'] as String,
      customerId: json['customer_id'] as String,
      recurringId: json['recurring_id'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'api_id': apiId,
      'cart_id': cartId,
      'cart_quantity': cartQuantity,
      'customer_id': customerId,
      'recurring_id': recurringId,
    };
  }
}

class ShoppingCart {
  final List<Product> products;
  final double tax;
  final double total;

  ShoppingCart({this.products, this.tax, this.total});

  factory ShoppingCart.fromJson(Map<String, dynamic> json) {
    return ShoppingCart(
      products: _toObjectList(json['products'], (e) => Product.fromJson(e)),
      tax: _toDouble(json['tax']),
      total: _toDouble(json['total']),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'products': _fromList(products, (e) => e.toJson()),
      'tax': tax,
      'total': total,
    };
  }
}

List _fromList(data, Function(dynamic) toJson) {
  if (data == null) {
    return null;
  }
  var result = [];
  for (var element in data) {
    var value;
    if (element != null) {
      value = toJson(element);
    }
    result.add(value);
  }
  return result;
}

double _toDouble(data) {
  if (data == null) {
    return null;
  }
  if (data is int) {
    return data.toDouble();
  }
  return data as double;
}

List<T> _toObjectList<T>(data, T Function(Map<String, dynamic>) fromJson) {
  if (data == null) {
    return null;
  }
  var result = <T>[];
  for (var element in data) {
    T value;
    if (element != null) {
      value = fromJson(element as Map<String, dynamic>);
    }
    result.add(value);
  }
  return result;
}

/*
ShoppingCart:
  products: List<Product>
  total: double
  tax: double

Product:
  cart_id: String
  api_id: String
  customer_id: String
  recurring_id: String
  cart_quantity: String

*/

答案 2 :(得分:0)

很简单:

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