使用json_serializable将Firestore Timestamp转Flutter DateTime(子类场景)
问题:Firestore Timestamp转DateTime时json_serializable子类序列化报错
我使用json_serializable处理Firestore返回的Timestamp到DateTime的转换,编写的父类和子类代码如下:
@JsonSerializable() class ParentClass { @TimestampSerializer() final DateTime createdAt; ParentClass({ required this.createdAt, }); factory ParentClass.fromJson(Map<String, dynamic> json) = _$ParentClassFromJson(json); } @JsonSerializable() class SubClass extends ParentClass { @TimestampSerializer() final DateTime updatedAt; SubClass({ required createdAt, required this.updatedAt, }) : super( createdAt: createdAt, ); factory SubClass.fromJson(Map<String, dynamic> json) = _$SubClassFromJson(json); }
调用SubClass.fromJson()方法时,出现以下错误:
Unhandled Exception: type 'Timestamp' is not a subtype of type 'DateTime'
我希望仅通过json_serializable实现Timestamp到DateTime的转换,请问该如何解决?
解决方案
1. 显式指定子类构造函数的父类参数类型
子类构造函数中的createdAt参数没有显式声明类型,导致json_serializable生成代码时,没有为这个参数应用父类的@TimestampSerializer()转换逻辑。修改子类构造函数,给createdAt加上DateTime类型声明:
SubClass({ required DateTime createdAt, // 显式指定类型 required this.updatedAt, }) : super( createdAt: createdAt, );
2. 确保TimestampSerializer实现正确
你的TimestampSerializer需要同时支持反序列化(Timestamp转DateTime)和序列化(DateTime转Timestamp),示例实现如下:
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:json_annotation/json_annotation.dart'; class TimestampSerializer implements JsonConverter<DateTime, Timestamp> { const TimestampSerializer(); @override DateTime fromJson(Timestamp timestamp) => timestamp.toDate(); @override Timestamp toJson(DateTime date) => Timestamp.fromDate(date); }
3. 重新生成序列化代码
修改代码后,执行以下命令重新生成*.g.dart文件,确保新的转换逻辑生效:
flutter pub run build_runner build
内容的提问来源于stack exchange,提问作者Seung Joo Noh
相关产品推荐
相关产品推荐

