美文网首页
Flutter中JSON数据到模型 复杂数据模型解析 模型嵌套

Flutter中JSON数据到模型 复杂数据模型解析 模型嵌套

作者: MacleChen | 来源:发表于2019-11-04 18:42 被阅读0次
    1. 基本数据模型类
    class BaseModel {
      String id;
      double createdTime;
      double updatedTime;
    
      BaseModel(this.id, this.createdTime, this.updatedTime) : super();
    
      BaseModel.fromJson(Map<String, dynamic> json)
          : id = json['id'],
            createdTime = json['createdTime'],
            updatedTime = json['updatedTime'];
    
      Map<String, dynamic> toJson() =>
          {
            'id': id,
            'createdTime': createdTime,
            'updatedTime': updatedTime,
          };
    }
    
    1. 具体数据模型(包括自模型解析和模型嵌套toJson)
    import '../base/BaseModel.dart';
    
    class FolderModel extends BaseModel {
      final String userId;
      final String name;
      final int level;
      final int status;
      final String fatherFolderId;
      final List<FolderModel> children;
    
      FolderModel.fromJson(Map<String, dynamic> json)
      : userId = json['userId'],
            name = json['name'],
            level = json['level'],
            status = json['status'],
            fatherFolderId = json['fatherFolderId'],
            children = json['children'] == null ? null : json['children'].forEach((data) {
              return FolderModel.fromJson(data);
            }), super.fromJson(json);
    
    
    
       @override
      Map<String, dynamic> toJson() {
        // TODO: implement toJson
         super.toJson();
         final Map<String, dynamic> dataJson = new Map();
    
         dataJson['userId'] = this.userId;
         dataJson['name'] = this.name;
         dataJson['level'] = this.level;
         dataJson['status'] = this.status;
         dataJson['fatherFolderId'] = this.fatherFolderId;
         if (this.children != null) {
           dataJson['children'] = this.children.map((data) => data.toJson()).toList();
         }
    
         return dataJson;
      }
    }
    

    相关文章

      网友评论

          本文标题:Flutter中JSON数据到模型 复杂数据模型解析 模型嵌套

          本文链接:https://www.haomeiwen.com/subject/vuodbctx.html