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

  1. 基本数据模型类
class BaseModel {
  String id;
  double createdTime;
  double updatedTime;

  BaseModel(this.id, this.createdTime, this.updatedTime) : super();

  BaseModel.fromJson(Map json)
      : id = json['id'],
        createdTime = json['createdTime'],
        updatedTime = json['updatedTime'];

  Map 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 children;

  FolderModel.fromJson(Map 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 toJson() {
    // TODO: implement toJson
     super.toJson();
     final Map 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;
  }
}

你可能感兴趣的:(react-native,原生与H5混合开发)