首页 > 解决方案 > 颤振嵌套json解析与三个模型类

问题描述

我在解析带有数组的 JSON 文件时遇到了麻烦。它看起来像这样:

{
  "params": [
    {
      "student_id": "1",
      "student_name": "name1",
      "student_dob": "dob1",
      "student_address": "address1"
    },
    {
      "student_id": "2",
      "student_name": "name2",
      "student_dob": "dob2",
      "student_address": "address2"
    }
  ],
  "error": {
    "code": 200,
    "message": ""
  }
}

标签: flutter

解决方案


您可以使用此工具从 json 生成类:https ://javiercbk.github.io/json_to_dart/

class YourNamedClassObject {
  List<Params> params;
  Error error;

  Autogenerated({this.params, this.error});

  Autogenerated.fromJson(Map<String, dynamic> json) {
    if (json['params'] != null) {
      params = new List<Params>();
      json['params'].forEach((v) {
        params.add(new Params.fromJson(v));
      });
    }
    error = json['error'] != null ? new Error.fromJson(json['error']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.params != null) {
      data['params'] = this.params.map((v) => v.toJson()).toList();
    }
    if (this.error != null) {
      data['error'] = this.error.toJson();
    }
    return data;
  }
}

class Params {
  String studentId;
  String studentName;
  String studentDob;
  String studentAddress;

  Params(
      {this.studentId, this.studentName, this.studentDob, this.studentAddress});

  Params.fromJson(Map<String, dynamic> json) {
    studentId = json['student_id'];
    studentName = json['student_name'];
    studentDob = json['student_dob'];
    studentAddress = json['student_address'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['student_id'] = this.studentId;
    data['student_name'] = this.studentName;
    data['student_dob'] = this.studentDob;
    data['student_address'] = this.studentAddress;
    return data;
  }
}

class Error {
  int code;
  String message;

  Error({this.code, this.message});

  Error.fromJson(Map<String, dynamic> json) {
    code = json['code'];
    message = json['message'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['code'] = this.code;
    data['message'] = this.message;
    return data;
  }
}

推荐阅读