首页 > 解决方案 > 通过返回类型的请求的通用 Json 反序列化器

问题描述

我一直在寻找解决方案,但找不到任何解决方案。

基本上我有一组解析 JSON 的模型,这很容易。

我希望能够发出诸如 'fetch(url)' 之类的请求并从请求中获取 T 作为类型。

例如

abstract class Json<T> {
  static fromJson(Map<String, dynamic> json) {}
  Map<String, dynamic> toJson();
}

我不能在静态中包含 T ,所以不知道该怎么做。

JSON 示例

@JsonSerializable()
class AppConfig implements Json<AppConfig> {
}

我无法弄清楚,也不知道在飞镖中是否有可能是;我们如何使用泛型返回默认类。例如:

Future<Map<String, dynamic>> fetch({
  required String url,
  Map<String, dynamic> body = const {},
}) async {
final response = await http.post(uri, headers: headers, body: body).timeout(Duration(seconds: 30));

responseBody = T.fromJson(response.body); // << Would return the type.

标签: jsonflutterdart

解决方案


推荐阅读