_CastError(类型“_InternalLinkedHashMap<dynamic, dynamic>”不是类型转换中类型 'Map<String, dynamic>' 的子类型)

_CastError (type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast)

我正在使用 Dart "json_serializable" 包在 Flutter 应用程序中反序列化以下 Firestore 数据结构。

{
googleBookId: jjl4BgAAQBAJ, 
providers: [
    {providerId: 2FA9fULKLLf7VUPPFnFRnv}, 
    {providerId: 8UYTGUHY7UJS432FVBJRnv}
]
}

下面是要映射的模型 class:

@JsonSerializable()
class Book {

  String googleBookId;
  List<Provider> providers;

  Book(this.googleBookId,
  {List<Provider> providers})
  : providers = providers ?? <Provider>[];

  factory Book.fromJson(Map<String, dynamic> map) => _$BookFromJson(map);

  Map<String, dynamic> toJson() => _$BookToJson(this);
}

@JsonSerializable()
class Provider {

  String providerId;

  Provider(this.providerId);

  factory Provider.fromJson(Map<String, dynamic> map) => _$ProviderFromJson(map);

  Map<String, dynamic> toJson() => _$ProviderToJson(this);
}

反序列化时出现以下错误

_CastError (type '_InternalLinkedHashMap' is not a subtype of type 'Map' in type cast)

Is there any other library that I can use to deserialize document?

好吧,我不知道你是否知道,但是 firestore 给你发了 Map 而不是 JSON。您正在尝试使用 JSON 序列化程序。 JSON 是 Map<String,dynamic> 而 firestore 发送 Map<dynamic,dynamic>. 所以你不能使用 parse it as json.

看看这个 https://medium.com/@atul.sharma_94062/how-to-use-cloud-firestore-with-flutter-e6f9e8821b27

other question 中所述,我能够通过编码为 JSON 字符串并在反序列化之前返回 JSON 对象来反序列化 Firestore 文档。

@Chiziaruhoma Ogbonda 感谢您的澄清,它帮助我以其他方式思考,而不是直接绑定到反序列化文档。

解决方案是使用 anyMap and explicitToJson 属性。

@JsonSerializable(explicitToJson: true, anyMap: true)
class Book {

}