0

我正在使用 Freezed 和 json_annotation 来序列化 API 对象。

@freezed
class Block with _$Block {
  const factory Order({
    @JsonKey(name: 'block_id') required String id,
    @JsonKey(name: 'sent_at') DateTime? sentAt,
    @JsonKey(name: 'created_at') DateTime? createdAt,
  }) = _Block;

  factory Block.fromJson(Map<String, dynamic> json) => _$BlockFromJson(json);
}

但有时,API 返回错误的类型,在这种情况下,是 int 而不是 string,这会导致错误。如果它接收到错误的类型而不是抛出错误,有没有办法将 createdAt 设置为 null?

4

1 回答 1

0

听起来您的 createdAt 可能会以 MillisecondsSinceEpoch 的形式出现。

通常最好确保您的数据类型始终相同,但如果您的数据源未知,那么您最好的选择可能是除了数据类型和稍后排序。

@JsonKey(name: 'created_at') DateTime?|int? createdAt,

if(createdAt is DateTime){
  //do something
} else if(createdAt is int){
  //do something
}
于 2021-11-26T19:35:00.210 回答