【发布时间】:2021-06-25 07:35:48
【问题描述】:
当我从服务器获得 JSON 响应时,我创建了使用来自服务器的 api 的颤振应用程序我解析响应并检索病假、服务名称、日期、用户、状态和一些关于病假的更多信息,问题是一些JSON 响应中的病患没有 doctororder 键或 medicalImagingOrder 键并且具有不同的键。当我尝试获取这些 JSON 键值时,程序会抛出一个错误,我应该如何处理?
这就是我创建对象的方式
class Datum {
Datum({
this.id,
this.sicke,
this.serviceName,
this.doctorOrder,
this.date,
this.user,
this.statusNumber,
this.status,
this.statusHistory,
this.insertDate,
this.statuses,
this.excessInvoice,
this.price,
this.shippingCosts,
this.vat,
this.netPrice,
this.totalPrice,
this.orderNumber,
this.v,
this.cancleReason,
this.medicalImagingOrder,
this.laboratoryOrder,
this.serviceProvider,
this.nurseOrder,
});
String id;
Sicke sicke;
String serviceName;
DoctorOrder doctorOrder;
DateTime date;
User user;
int statusNumber;
StatusEnum status;
List<StatusHistory> statusHistory;
DateTime insertDate;
List<StatusElement> statuses;
List<dynamic> excessInvoice;
int price;
int shippingCosts;
int vat;
int netPrice;
int totalPrice;
int orderNumber;
int v;
String cancleReason;
Order medicalImagingOrder;
LaboratoryOrder laboratoryOrder;
String serviceProvider;
Order nurseOrder;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["_id"],
sicke: json["sicke"] == null ? null : Sicke.fromJson(json["sicke"]),
serviceName: json["serviceName"],
doctorOrder: json["doctorOrder"] == null ? null : DoctorOrder.fromJson(json["doctorOrder"]),
date: DateTime.parse(json["date"]),
user: userValues.map[json["user"]],
statusNumber: json["statusNumber"],
status: statusEnumValues.map[json["status"]],
statusHistory: List<StatusHistory>.from(json["statusHistory"].map((x) => StatusHistory.fromJson(x))),
insertDate: DateTime.parse(json["insertDate"]),
statuses: List<StatusElement>.from(json["statuses"].map((x) => StatusElement.fromJson(x))),
excessInvoice: List<dynamic>.from(json["excessInvoice"].map((x) => x)),
price: json["price"],
shippingCosts: json["shippingCosts"],
vat: json["VAT"],
netPrice: json["netPrice"],
totalPrice: json["totalPrice"],
orderNumber: json["orderNumber"],
v: json["__v"],
cancleReason: json["cancleReason"] == null ? null : json["cancleReason"],
medicalImagingOrder: json["medicalImagingOrder"] == null ? null : Order.fromJson(json["medicalImagingOrder"]),
laboratoryOrder: json["laboratoryOrder"] == null ? null : LaboratoryOrder.fromJson(json["laboratoryOrder"]),
serviceProvider: json["serviceProvider"] == null ? null : json["serviceProvider"],
nurseOrder: json["nurseOrder"] == null ? null : Order.fromJson(json["nurseOrder"]),
);
【问题讨论】:
-
您收到了对象列表? `基准`列表?
-
你能分享一个错误日志吗?
-
你可以试试这个解决方案。 stackoverflow.com/a/66632608/1737201
-
是的,我收到了@mezoni 对象列表
-
@MasoudH 答案描述了对象列表的解决方案。
final list = response.body.jsonList((e) => Datum.fromJson(e));这比你想象的要容易。