首页 > 解决方案 > 如何在 json_serializable 颤振中将 int 时间戳转换为 DateTime

问题描述

如何将整数时间戳转换为日期时间。

示例代码:

@JsonSerializable(nullable: false)
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  Map<String, dynamic> toJson() => _$PersonToJson(this);    
}  

如何将 dateOfBirth 整数时间戳转换为 DateTime?

标签: jsondartflutter

解决方案


要将int时间戳转换为DateTime,您需要将返回DateTime结果的静态方法传递给fromJson@JsonKey 注释中的参数。

此代码解决了问题并允许转换。

@JsonSerializable(nullable: false)
    class Person {
      final String firstName;
      final String lastName;
      @JsonKey(fromJson: _fromJson, toJson: _toJson)
      final DateTime dateOfBirth;
      Person({this.firstName, this.lastName, this.dateOfBirth});
      factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
      Map<String, dynamic> toJson() => _$PersonToJson(this);

      static DateTime _fromJson(int int) => DateTime.fromMillisecondsSinceEpoch(int);
      static int _toJson(DateTime time) => time.millisecondsSinceEpoch;

    }   

用法

Person person = Person.fromJson(json.decode('{"firstName":"Ada", "lastName":"Amaka", "dateOfBirth": 1553456553132 }'));

推荐阅读