如何在flutter中反序列化json中的对象列表 [英] How to Deserialize a list of objects from json in flutter

查看:22
本文介绍了如何在flutter中反序列化json中的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the dart package json_serializable for json serialization. Looking at the flutter documentation it shows how to deserialize a single object as follow:

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 不够熟悉,无法弄清楚如何对项目列表而不是单个实例执行相同的操作.

However, I am not familiar enough with dart to figure out how to do the same for a list of items instead of a single instance.

推荐答案

好吧,您的服务将相应地处理作为映射或映射列表的响应主体.根据您拥有的代码,您计算了 1 个项目.

Well, your service would handle either the response body being a map, or a list of maps accordingly. Based on the code you have, you are accounting for 1 item.

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

If the response body is iterable, then you need to parse and walk accordingly, if I am understanding your question correctly.

示例:

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

其中帖子是帖子列表.

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

EDIT: I wanted to add a note of clarity here. The purpose here is that you decode the response returned. The next step, is to turn that iterable of JSON objects into an instance of your object. This is done by creating fromJson methods in your class to properly take JSON and implement it accordingly. Below is a sample implementation.

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 有点抽象,赞成为需要完成的任务提供更好的实用程序.所以我的语法可能有点偏差,但这是伪代码.

I am a bit abstracted from Dart these days in favor of a better utility for the tasks needing to be accomplished. So my syntax is likely off just a little, but this is Pseudocode.

这篇关于如何在flutter中反序列化json中的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆