Flutter复杂嵌套格式的fromJson和toJson

4,004 阅读1分钟

背景:由于flutter的数据模型构建无法像在Android studio使用gsonformat复制拷贝一键生成,所以是比较麻烦的,目前比较流行的方式是像我之前一篇文章说的那样,使用flutter packages pub run build_runner build自动生成,地址附上:juejin.cn/post/685997…, 但是这种方式也有很多风险,另外一点就是再次构建生成容易报错,而且是无缘无故报错的那种[狗头]。所以尝试了手动撸一边复杂的嵌套json格式的~~~

class UserInfo {
  String staffCode;
  List<ChildApp> childApp;
  List<UserRoleResp> userRoleRespList;
  UniApp uniApp;

  UserInfo(
      {this.staffCode,
      this.childApp,
      this.userRoleRespList,
      this.uniApp});

  UserInfo.fromJson(Map<String, dynamic> json) {
    staffCode = json["staffCode"];
    var childAppList = json['childApp'] as List; //json转数组变量
    var userRoleRespList = json['userRoleRespList'] as List;

    //需要遍历json串,将每个对象的json串fromJson再add到数组字段中
    if (childAppList.isNotEmpty) {
      this.childApp = new List<ChildApp>();
      childAppList.forEach((i) => this.childApp.add(new ChildApp.fromJson(i)));
    }
    if (userRoleRespList.isNotEmpty) {
      this.userRoleRespList = new List<UserRoleResp>();
      userRoleRespList
          .forEach((i) => this.userRoleRespList.add(UserRoleResp.fromJson(i)));
    }
    uniApp = UniApp.fromJson(json["uniApp"]);
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["staffCode"] = this.staffCode;
    data["uniApp"] = this.uniApp;
    //将数组转Map
    if (this.childApp.isNotEmpty) {
      data['childApp'] = this.childApp.map((e) => e.toJson()).toList();
    }
    if (this.userRoleRespList.isNotEmpty) {
      data['userRoleRespList'] =
          this.userRoleRespList.map((e) => e.toJson()).toList();
    }
    return data;
  }
}

看了代码基本都清楚了,对象的比较容易,主要是数组嵌套,数组fromJson时将json数组转下List类型,然后foreach数组将每个数组里的对象fromJson后,重新add到已经new的数组对象字段中。tojson时将数组map后获取到每个map对象,然后将每个map对象toJson完了最后toList,记得判空~~~