我如何在Flutter中处理API中同一个键的多个数据类型?

0s7z1bwu  于 2022-11-30  发布在  Flutter
关注(0)|答案(2)|浏览(186)

让我们来解释一下我的问题...假设有一个json对象,如
from this picture i want to handle offer_price keyenter image description here显示器

{
  "product": [
    {
      "id": 1,
      "price": 100.0,
      "offer_price": 40
    },
    {
      "id": 2,
      "price": 80.0,
      "offer_price": 10.50
    },
    {
      "id": 3,
      "price": 200.0,
      "offer_price": "40.5"
    },
    {
      "id": 4,
      "price": 100.0,
      "offer_price": null,
      
    }
  ]
}
zaqlnxep

zaqlnxep1#

class Product {
  int? id;
  int? price;

  // if you need the value as String
  String? offerPriceAsString;

  // Value as a double
  double? offerPrice;

  Product({this.id, this.price, this.offerPrice});

  Product.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    price = json['price'];
    double.parse("1.0");
    // Any value to String
    offerPriceAsString = json['offer_price'].toString();
    // String to Double
    offerPrice = double.parse(json['offer_price'].toString());
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['price'] = price;
    data['offer_price'] = offerPrice;
    return data;
  }
}
ecbunoof

ecbunoof2#

在dart数据模型的offer_price字段中,将其数据类型设置为dynamic,这样就可以将动态数据设置为run类型。在任何地方使用此变量时,只需检查变量的runtimeType,并通过类型转换或仅将其用于.toString()
例如班级:

class Products {
  Products({this.product});

  Products.fromJson(Map<String, dynamic> json) {
    if (json['product'] != null) {
      product = <Product>[];
      json['product'].forEach((v) {
        product!.add(Product.fromJson(v));
      });
    }
  }
  
  List<Product>? product;
  
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    if (this.product != null) {
      data['product'] = this.product!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Product {
  Product({this.id, this.price, this.offerPrice});
  
  Product.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    price = json['price'];
    offerPrice = json['offer_price'];
  }
  
  int? id;
  int? price;
  dynamic? offerPrice;

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = this.id;
    data['price'] = this.price;
    data['offer_price'] = this.offerPrice;
    return data;
  }
}

对于消费它只是尝试:

Products products = List<Products>[];

//assign products = Products.fromJson(jsonData);

//using
products[i].offerPrice == null
? "null"
: products[i].offerPrice.runtimeType == String
   ? products[i].offerPrice.toString()
   : products[i].offerPrice.runtimeType == Int
      ? int.parse(products[i].offerPrice)
      : products[i].offerPrice.runtimeType == Double
           ? double.parse(products[i].offerPrice)
           : ""

相关问题