flutter - 颤振嵌套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": ""
}
}
解决方案
您可以使用此工具从 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;
}
}
推荐阅读
- r - 如何通过考虑 R 中数据的层次结构来重新采样和创建引导程序?
- python - 错误 = 'str' 对象没有属性 'to_frame'
- java - Android获取特殊蓝牙设备信号(RSSI)
- excel - 将值字段添加到数据透视表时出现错误
- node.js - Axios - CORS 政策问题
- javascript - 使用 PM2 API 重新启动,在 PM2 中运行时也重新启动脚本自身
- reactive-programming - 混合两个 Mono 并返回第一个与第一个主体中的第二个
- mysql - 找不到 my.cnf 的 mySQL 配置文件以允许在 mac Big Sur 上进行远程访问
- linux - g++ "在 Linux 上对 `typeinfo for xercesc_3_2::XMLException" 的未定义引用
- python - 图像金字塔计算错误“输入参数的大小不匹配”