[英]I want to handle dateTime null value in JSON parsing in flutter
我需要幫助處理 DateTime JSON 解析的空值。 由於一些數據沒有createDate
,我在顯示數據時遇到問題這是我的代碼:
factory OfaModel.fromJson(Map<String, dynamic> json) => TestModel(
createdDate: DateTime.parse(json["CreatedDate"]),
recordtypeBm: json["recordtype_bm"],
amsCustodialHistoryBm: List<String>.from(json["AMSCustodialHistoryBM"].map((x) => x)),
subjectCode: json["SubjectCode"]
recordtypeBi: json["recordtype_bi"],
);
你只需要提出這樣的條件:
json["CreatedDate"] == null ? null : DateTime.parse(json["CreatedDate"])
您可以使用DateTime.tryParse()
createdDate : DateTime.tryParse(json["CreatedDate"]),
//DateTime.parse('') -> Returns (Uncaught Error: FormatException: Invalid date format)
//DateTime.tryParse('') -> Returns null instead of Exception
只是檢查它是否不是,
factory OfaModel.fromJson(Map<String, dynamic> json) => TestModel(
createdDate:json["CreatedDate"] != null ? DateTime.parse(json["CreatedDate"]) : null,
recordtypeBm: json["recordtype_bm"],
amsCustodialHistoryBm: List<String>.from(json["AMSCustodialHistoryBM"].map((x) => x)),
subjectCode: json["SubjectCode"]
recordtypeBi: json["recordtype_bi"],
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.