json - 如何在 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?
解决方案
要将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 }'));
推荐阅读
- java - 从 Maven exec 连接到 MongoDB 失败,但不是从 jar
- kotlin - 如何在文件路径中运行带有空格的 bat 文件?
- google-cloud-firestore - 带有绑定的VuexFire同步不起作用
- c# - 在 C# 中迭代 spark 数据框列
- palantir-foundry - 是否可以通过 Foundry 中的编辑表单的派生值来更改对象的标题属性?
- rpg - Miworkplace:发生错误。查看日志文件 (RPG)
- javascript - 如何找到具有 Id 和 token 值的网站?
- scala - scala3 扩展方法类型参数
- php - PHP sendmail 有效,但作为 Cronjob 失败:“sh: 1: /usr/sbin/sendmail: not found”
- c++ - 打印链表中结构的元素时出现C++分段错误