从Flutter中的Json错误解析DateTime

时间:2019-03-28 14:54:18

标签: json datetime parsing flutter

我正在尝试从Json到我的flutter应用程序获取简单的DateTime格式,但是我仍然尝试得到这种类型的格式:2019-03-28 10:06:27.090Z

我收到此错误:

E/flutter (27849): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: ApiException 500: Exception during deserialization. (Inner exception: {innerException})
E/flutter (27849): 
E/flutter (27849): #0      DateTime.parse (dart:core/date_time.dart:335:7)*

这是代码示例:

  MyClass.fromJson(Map<String, dynamic> json) {
    if (json == null) return;
    name = json['name'];
    deletionTime = json['deletionTime'] == null ? null : DateTime.parse(json['deletionTime']);
    lastModificationTime = json['lastModificationTime'] == null ? null : DateTime.parse(json['lastModificationTime']);
    creationTime = json['creationTime'] == null ? null : DateTime.parse(json['creationTime']);
    id = json['id'];
  }

我希望Json能成功解析到DateTime。

1 个答案:

答案 0 :(得分:1)

DateTime.parse仅接受String自变量。由于值是动态检查类型,请使用json['key'].runtimeType并尝试以下解决方案。

DateTime.parse(json['deletionTime'].toString());

DateTime.parse(json['creationTime'].toString());