如何在json_serializable Flatter中将int-timestamp转换为DateTime

如何在json_serializable Flatter中将int-timestamp转换为DateTime,json,dart,flutter,Json,Dart,Flutter,如何将整数时间戳转换为日期时间 示例代码: @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<Str

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

示例代码:

@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);    
}  
@JsonSerializable(可空:false)
班主任{
最后一个字符串名;
最后一个字符串lastName;
出生的最后日期时间日期;
Person({this.firstName,this.lastName,this.dateOfBirth});
factory Person.fromJson(Map json)=>\uu$PersonFromJson(json);
映射到JSON()=>$PersonToJson(这个);
}  

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

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

这段代码解决了这个问题并允许转换

@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;

    }   
我用这个:

@JsonSerializable()
班主任{
@JsonKey(fromJson:dateTimeFromTimestamp)
出生日期时间;
...
}
DateTime dateTimeFromTimestamp(时间戳时间戳){
返回timestamp==null?null:timestamp.toDate();
}

在我的案例中,它不适用于firebase的数据,时间戳值为datetime(本地)失败。
Person person = Person.fromJson(json.decode('{"firstName":"Ada", "lastName":"Amaka", "dateOfBirth": 1553456553132 }'));