json - 如何在 flutter 中反序列化来自json的对象列表

标签 json dart flutter

我正在使用 dart 包 json_serializable 进行 json 序列化。查看 flutter 文档,它显示了如何反序列化单个对象,如下所示:

Future<Post> fetchPost() async {
  final response =
  await http.get('https://jsonplaceholder.typicode.com/posts/1');

  if (response.statusCode == 200) {
  // If the call to the server was successful, parse the JSON
  return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

但是,我对 dart 不够熟悉,无法弄清楚如何对项目列表而不是单个实例执行相同操作。

最佳答案

好吧,您的服务将处理作为 map 的响应正文或相应的 map 列表。根据您拥有的代码,您计入 1 项。

如果响应正文是可迭代的,那么如果我正确理解您的问题,您需要相应地解析和遍历。

例子:

Iterable l = json.decode(response.body);
List<Post> posts = List<Post>.from(l.map((model)=> Post.fromJson(model)));

帖子是帖子列表。

编辑:我想在这里添加一个清晰的说明。这里的目的是解码返回的响应。下一步是将 JSON 对象的可迭代对象转换为对象的实例。这是通过在您的类中创建 fromJson 方法来正确获取 JSON 并相应地实现它来完成的。下面是一个示例实现。

class Post {
  // Other functions and properties relevant to the class
  // ......
  /// Json is a Map<dynamic,dynamic> if i recall correctly.
  static fromJson(json): Post {
    Post p = new Post()
    p.name = ...
    return p
  }
}

这些天我有点从 Dart 中抽象出来,支持更好的实用程序来完成需要完成的任务。所以我的语法可能有点偏差,但这是伪代码。

关于json - 如何在 flutter 中反序列化来自json的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51053954/

相关文章:

php - Json导入mysql

javascript - 映射单元格以在 HTML 表格中显示 JSON 数据

json - Spark 2.1.1 : Parsed JSON values do not match with class constructor

flutter - 如何按日期时间 (String) 对 List<Map<String, dynamic>> 进行排序

google-maps - 如何从纬度和经度中提取位置名称

android-studio - Flutter doctor 错误 - 找不到 Android sdkmanager 工具。 window

flutter - 错误 : The argument type 'String Function(String)' can't be assigned to the parameter type 'String? Function(String?)?'

c# - 如何从 ASP.net MVC 程序中获取普通 c# 程序中的 JSON 数据?

dart - Flutter:协议(protocol),它们存在吗?

flutter - 是否可以读取由 FittedBox 设置的文本小部件的字体大小?