【问题标题】:Different Datastructure Serialization between Client and Database客户端和数据库之间不同的数据结构序列化
【发布时间】:2020-07-19 17:00:47
【问题描述】:

在我的客户中,我有一个类,例如 ClassA,其中包含一个属性 List<ClassB>

我的目标是将对象 ClassA 保存在 Firestore 中。此外,我希望将 List<ClassB> 属性作为 Map 而不是 Array 保存到 Firestore 中(也可以在客户端内将其保存为 List<Object>)。

既然我想使用json_serializable 库,有没有办法为给定类的属性指定如何进行序列化/反序列化并选择应为 Firestore 映射使用哪种键?

【问题讨论】:

  • 为什么不直接将列表转换为地图,然后提供给 Firestore?
  • @DougStevenson 这就是我想要做的,但我不确定如何使用 json_serializable。不过,我想在我的客户端中保留 List 结构。
  • 您不必放弃该列表。只需使用它来编写地图以写入 Firestore。
  • @DougStevenson 对,所以我们说的是同一件事 :) 我的问题是,是否可以使用上面提到的库而不是手动编写来半自动地执行此操作。
  • 据我所知,该库处理 JSON,而不是其他对象 Dart 对象。 Firestore 不处理 JSON,它处理 Dart 对象。

标签: flutter dart serialization google-cloud-firestore


【解决方案1】:

为了将 List 转换为 Map,您不需要将对象转换为 JSON 然后再返回。

您可以使用Map.fromIterable() 或collection-for 将List 转换为Map。见其他SO answer

【讨论】:

  • 在这种情况下你是对的。虽然这不是我想要解释的。我在谈论我想在我的数据库和我的客户端中使用的不同数据结构。对于这种情况,我需要toMap/fromMaptoJson/fromJson。我确实找到了解决方案。现在也在这里发布。
【解决方案2】:

我确实找到了问题的答案。

因此,为了将json_serializable 用于剩余的ClassA 属性,我必须对属性List<ClassB> 使用@JsonKey 注释。通过这样做,我可以使用自定义的fromJson/toJson 方法。在这种方法中,我可以将myList 转换为适用于 Firestore 的 Map。

这就是我必须使用它的方式:

@JsonKey( fromJson: _firestoreMapToList, toJson: _listToFirestoreMap)
final List<ClassB> myList;

_firestoreMapToList_listToFirestoreMap 方法将“覆盖”classA.g.dart 文件的自动生成方法,该文件在使用json_serializable 库并在终端中输入此flutter pub run build_runner watch 时也会自动生成。

这就是方法的样子:

static List<ClassB> _firestoreMapToList(Map<String, dynamic> firestoreMap) {
 if (firestoreMap != null) {
  return List<ClassB>.from(firestoreMap?.entries
      ?.map((e) => ClassB.fromJson(e.value))
      ?.toList());
 }
 return null;
}


static Map<String, Map<String, dynamic>> _listToFirestoreMap(List<ClassB> list) {
 if (list != null) {
  return Map<String, Map<String, dynamic>>.from(list?.asMap()?.map(
      (key, classB) => MapEntry(
          classB.firebaseId,
          classB.toJson())))
    ..removeWhere((key, value) => key == null); // remove map entries with null as key
 }
 return null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多