我正在尝试解析来自Web服务的响应,并以表格形式将其显示出来。 以下是我的回复
{
"success": true,
"data": [{
"id": 5,
"roll_no": "R1005",
"user_id": "5"
},
{
"id": 6,
"roll_no": "R1006",
"user_id": "6"
},
{
"id": 7,
"roll_no": "R1007",
"user_id": "7"
},
{
"id": 8,
"roll_no": "R1008",
"user_id": "8"
}
]
}
当我试图将上述json解析为表格时,我只能打印成功一词
Map<String, dynamic> response = await AppHttp().getApi(donationListURL);
donationListlModel = DonationListlModel.fromJson(response);
和
DonationListlModel.fromJson(Map<String, dynamic> json) {
success = json['success'];
print('donation list model success $success');
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
这是我收到的错误消息-
type 'List<dynamic>' is not a subtype of type 'Data'
以下是我的模型文件
class DonationListlModel {
bool success;
Data data;
DonationListlModel({this.success, this.data});
DonationListlModel.fromJson(Map<String, dynamic> json) {
success = json['success'];
print('donation list model success $success');
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
if (this.data != null) {
data['data'] = this.data.toJson();
}
print('donation list model data $data');
return data;
}
}
class Data {
String id;
String rollNo;
String userId;
Data(
{this.id,
this.rollNo,
this.userId,
this.parentId});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
rollNo = json['roll_no'];
userId = json['user_id'];
parentId = json['parent_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['roll_no'] = this.rollNo;
data['user_id'] = this.userId;
data['parent_id'] = this.parentId;
print('donation list model data toJSON $data');
return data;
}
}
什么是错误
答案 0 :(得分:0)
在您的JSON中,“数据”是List
个对象中的Data
个。因此,您需要将数据变量的数据类型更改为List<Data>
,如下所示
class DonationListlModel {
bool success;
List<Data> data;
DonationListlModel({this.success, this.data});
DonationListlModel.fromJson(Map<String, dynamic> json) {
success = json['success'];
print('donation list model success $success');
if (this.data != null) {
json['data'] = this.data.map((v) => v.toJson()).toList();
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
print('donation list model data $data');
return data;
}
}
class Data {
String id;
String rollNo;
String userId;
Data(
{this.id,
this.rollNo,
this.userId});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
rollNo = json['roll_no'];
userId = json['user_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['roll_no'] = this.rollNo;
data['user_id'] = this.userId;
print('donation list model data toJSON $data');
return data;
}
}