我需要 API 回應處理的幫助。我創建了模型類來轉換 API res。我的問題在于型別 API 回應已更改,例如
如果型別 = '應用程式'
{
"status": "success",
"message": "Active loan Fetched",
"data": {
"Application": {
"id": "",
"coapp_status": null,
"status": "pending-document",
"approved_amount": "3000",
"processing_fees": "450",
},
"type": "Application"
},
"timestamp": "2022-05-07 13:05:36",
"require_update": "yes"
}
如果型別 = '貸款'
{
"status": "success",
"message": "Loan Fetched",
"data": {
"Loan": {
"id": "",
"policy_id": "",
"application_id": "",
"user_id": "",
"approved_amount": "8000",
"disbursment_amount": "6552",
"processing_fees": "1200",
"interest_rate": "480",
"pre_emi_interest": "31.5616",
"totalAmount": 8480,
"gst_processing_fees": 216,
"totalDisbursment": 6552.4384,
"current_emi_date": "10 Jun 22",
"current_emi_amount": "5088",
"current_emi_id": "51298",
"viewid": "",
"customermessage": "Your loan have been approved for Rs.8000"
},
"type": "Loan"
}
在資料類中,物件將根據型別進行更改
錯誤日志:
Unhandled Exception: type 'Null' is not a subtype of type 'Map<String, dynamic>'
型號類:
Application? application;
Loan? loan;
String? type;
String? sanctionLetter;
factory Data.fromJson(Map<String?, dynamic> json) => Data(
application: Application.fromJson(json["Application"]), => **Error if application not Found**
loan: Loan.fromJson(json["Loan"]), **Error if Loan not found**
type: json["type"],
sanctionLetter: json["sanction_letter"],
);
Map<String?, dynamic> toJson() => {
"Application": application!.toJson(),
"Loan": loan!.toJson(),
"type": type,
"sanction_letter": sanctionLetter,
};
}
uj5u.com熱心網友回復:
我認為問題在于空值檢查:
factory Data.fromJson(Map<String?, dynamic> json) => Data(
application: json["Application"] ? Application.fromJson(json["Application"]) : null, // **Because it can be null**
loan: json["Loan"] ? Loan.fromJson(json["Loan"]) : null, // **Because it can be null**
type: json["type"],
sanctionLetter: json["sanction_letter"],
);
更新
application: json["Application"] != null ? Application.fromJson(json["Application"]) : null, // **Because it can be null**
loan: json["Loan"] != nul ? Loan.fromJson(json["Loan"]) : null,
抱歉之前的回答,我忘了檢查 null
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470167.html
上一篇:如何從json回應陣列中提取id
下一篇:如何訪問嵌套陣列
