0

我在我的 Flutter 应用程序中使用 moor 作为本地存储,我创建了表,并 moor 为我生成了模型,使用 fromJson 工厂和 toJson 方法。例子:

class Addresse extends DataClass implements Insertable<Addresse> {
  final int id;
  final String street1;
  final String street2;
  final String city;
  final String zip;
  final String country;
  final String state;
  //constructor generated here
  // fromData method here
  // toColumns method here
  // toCompanion method here

  factory Addresse.fromJson(Map<String, dynamic> json,
      {ValueSerializer serializer}) {
    serializer ??= moorRuntimeOptions.defaultSerializer;
    return Addresse(
      id: serializer.fromJson<int>(json['id']),
      street1: serializer.fromJson<String>(json['street1']),
      street2: serializer.fromJson<String>(json['street2']),
      city: serializer.fromJson<String>(json['city']),
      zip: serializer.fromJson<String>(json['zip']),
      country: serializer.fromJson<String>(json['country']),
      state: serializer.fromJson<String>(json['state']),
    );
  }

  @override
  Map<String, dynamic> toJson({ValueSerializer serializer}) {
    serializer ??= moorRuntimeOptions.defaultSerializer;
    return <String, dynamic>{
      'id': serializer.toJson<int>(id),
      'street1': serializer.toJson<String>(street1),
      'street2': serializer.toJson<String>(street2),
      'city': serializer.toJson<String>(city),
      'zip': serializer.toJson<String>(zip),
      'country': serializer.toJson<String>(country),
      'state': serializer.toJson<String>(state),
    };
  }

  //copyWith method here
  //toString method here

  //hash method here
  //equals method here
}

我正在使用 chopper 来使用 API,并创建一个 chopper 客户端,我需要告诉它如何序列化和反序列化请求/响应正文。Chopper 通过在创建 Chopper 客户端时设置转换器属性来提供此功能:

ChopperClient(
  baseUrl: BASE_URL,
  services: services,
  interceptors: [
    HttpLoggingInterceptor(),
  ],
  converter: //add the converter here,
);

我想让 chopper 在我的模型中使用 moor 生成的 fromJson 和 toJson,但我似乎没有找到正确的方法来做到这一点。任何提示,指南表示赞赏。

4

0 回答 0