Flutter_model层

90 阅读2分钟

iOS 中有很多优秀的model解析框架如 YYModel、MJExtesion、ObjectMapper。flutter中则需要自己处理

{
    "result": {
        "_id": "6333cc2d9e8e3a0f80512495",
        "title": "Redmi K50 至尊版",
        "cid": "59f1e4919bfd8f3bd030eed6",
        "price": 2666,
        "old_price": 6000,
        "is_best": 1,
        "is_hot": 0,
        "is_new": 0,
        "attr": [
            {
                "cate": "颜色",
                "list": [
                    "土豪金",
                    "玫瑰红",
                    "磨砂黑"
                ]
            },
            {
                "cate": "内存",
                "list": [
                    "16G",
                    "32G",
                    "64G"
                ]
            }
        ],
        "status": 1,
        "pic": "public\\upload\\iFrB4izNiGzov22F2aJXX0ta.png",
        "content": "<p></p><p><img src=\"https://img30.360buyimg.com/sku/jfs/t1/111643/6/28163/77482/62f4dde7E242fa1e6/4c36c9375e7bc193.jpg\" alt=\"\" /><br /></p><p><img src=\"https://img30.360buyimg.com/sku/jfs/t1/90443/37/31195/87452/62f4dde5Ec8c7aaf1/703e54cd6e29a50e.jpg\" alt=\"\" /><br /></p><p><br /></p><p><img src=\"https://img30.360buyimg.com/sku/jfs/t1/190265/6/27733/47769/62f4dde5E8d804fbd/58c58ffce2e7f6c7.jpg\" alt=\"\" /><br /></p>",
        "cname": "手机/电脑",
        "sub_title": "骁龙8+旗舰处理器 1亿像素光学防抖 120W+5000mAh 12GB+256GB 雅黑 小米红米K50 Ultra",
        "specs": "<p><img src=\"https://img30.360buyimg.com/sku/jfs/t1/159650/24/29598/241843/62f4dddeE4981f731/f617df71c2c2cab0.jpg\" alt=\"\" /></p><p><img src=\"https://img30.360buyimg.com/sku/jfs/t1/107654/14/32509/41129/62f4dde6E58e1f9c2/b2003a003fcb8eca.jpg\" alt=\"\" /><br /></p>"
    }
}

json 转 dart

json 转 dart

也可以手动制作一波

从内部到外部转换

{ "cate": "颜色", "list": [ "土豪金", "玫瑰红", "磨砂黑" ] }

class ProductContentAttr {
  String? cate;
  List<String>? list;
  List<String>? list2;
  /// 构造方法
  ProductContentAttr({this.cate, this.list, this.list2});
  /// json转模型
  ProductContentAttr.fromJson(Map<String, dynamic> json) {
    cate = json['cate'];
    /// cast
    list = json['list'].cast<String>();
    /// 迭代器
    List list2 = json['list'] ?? [];
    list = list2.map((e) => e.toString()).toList();
  }
  /// json 转模型
  factory ProductContentAttr.fromJson2(Map json) {
    return ProductContentAttr(
      cate: json['cate'] ?? '',
      list: json['list'] ?? [],
      list2: json['list'],
    );
  }
  /// 模型转json
  Map<String, dynamic> toJson() {
    Map<String, dynamic> data = <String, dynamic>{};
    data['cate'] = cate;
    data['list'] = list;
    return data;
  }
}

List<String> cast

as执行强制转换,该强制转换在执行运行时检查后更改对象的静态(编译时已知)类型。它不影响对象的标识。对 * 集合 *(例如ListMapSet)使用as会强制转换该集合对象本身,而不是其元素。
集合提供了一个.cast方法,该方法为集合返回一个新对象(一个“视图”),该集合为每个 element 执行as强制转换。

list = json['list'].cast<String>();

迭代器 转换

List list2 = list = json['list'] ?? [];
list = list2.map((e) => e.toString()).toList();

List<Object>

List list = json['attr'] ?? [];
if (list.isNotEmpty) {
  attr = list.map((e) => ProductContentAttr.fromJson(e)).toList();
}

完整的解析


import 'package:jingdong/Utils/StringExtension.dart';

import '../Config/config.dart';

class ProductContentModel {
  ProductContentItem? result;
  ProductContentModel({this.result});
  ProductContentModel.fromJson(Map<String, dynamic> json) {
    result = json['result'] != null ? ProductContentItem.fromJson(json['result']) : null;
  }
  /// 模型转json
  Map<String, dynamic> toJson() {
    Map<String, dynamic> data = <String, dynamic>{};
    data['result'] = result?.toJson();
    return data;
  }
}

class ProductContentItem {
  String? id;
  String title = '';
  String? cid;
  Object? price;
  Object? oldPrice;
  int? isBest;
  int? isHot;
  int? isNew;
  int? status;
  String pic = '';
  String? content;
  String? name;
  String? subTitle;
  String? specs;
  List<ProductContentAttr> attr = [];
  String test = '';

  ProductContentItem({
      this.id,
      required this.title,
      this.cid,
      this.price,
      this.oldPrice,
      this.isBest,
      this.isHot,
      this.isNew,
      this.status,
      required this.pic,
      this.content,
      this.name,
      this.subTitle,
      this.specs});
  /// json转模型
  ProductContentItem.fromJson(Map<String, dynamic> json) {
    id = json['_id'];
    title = json['title'];
    cid = json['cid'];
    price = json['price'];
    oldPrice = json['old_price'];
    isBest = json['is_best'].toString().toInt();
    isHot = json['is_hot'].toString().toInt();
    isNew = json['is_new'].toString().toInt();
    status = json['status'].toString().toInt();
    //pic = json['pic'];
    content = json['content'];
    name = json['cname'];
    subTitle = json['sub_title'];
    specs = json['specs'];

    List list = json['attr'] ?? [];
    if (list.isNotEmpty) {
      attr = list.map((e) => ProductContentAttr.fromJson(e)).toList();
    }

    String pic = json['pic'];
    if (pic.contains('\')) {
      pic = pic.replaceAll('\', '/');
      if (!pic.isUrl()) {
        pic = '${Config.domain}$pic';
      }
      this.pic = pic;
    }
  }

  /// 模型转json
  Map<String, dynamic> toJson() {
    Map<String, dynamic> data = <String, dynamic>{};
    data['_id'] = id;
    data['title'] = title;
    data['cid'] = cid;
    data['price'] = price;
    data['old_price'] = oldPrice;
    data['is_best'] = isBest;
    data['is_hot'] = isHot;
    data['is_new'] = isNew;
    data['status'] = status;
    data['pic'] = pic;
    data['content'] = content;
    data['cname'] = name;
    data['subTitle'] = subTitle;
    data['specs'] = specs;
    data['attr'] = attr.map((e) => e.toJson()).toList();
    return data;
  }
}

class ProductContentAttr {
  String? cate;
  List<String>? list;
  List<ProductContentAttrItem> attr = [];
  /// 构造方法
  ProductContentAttr({this.cate, this.list});
  /// json转模型
  ProductContentAttr.fromJson(Map<String, dynamic> json) {
    cate = json['cate'];
    /// cast
    list = json['list'].cast<String>();
    /// 迭代器
    List listJson = json['list'] ?? [];
    list = listJson.map((e) => e.toString()).toList();
    if (list != null) {
      attr = list!.map((e) => ProductContentAttrItem(e, false)).toList();
    }
  }
  /// json 转模型 工厂模式
  factory ProductContentAttr.fromJson2(Map json) {
    return ProductContentAttr(
      cate: json['cate'] ?? '',
      list: json['list'].cast<String>()
    );
  }
  /// 模型转json
  Map<String, dynamic> toJson() {
    Map<String, dynamic> data = <String, dynamic>{};
    data['cate'] = cate;
    data['list'] = list;
    return data;
  }
}

class ProductContentAttrItem {
  String name = '';
  bool check = false;
  ProductContentAttrItem(this.name, this.check);
}