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

查看:600
本文介绍了如何在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 an 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 = l.map((Map model)=> Post.fromJson(model)).toList();

其中posts是帖子列表.

where posts is a LIST of posts.

编辑:我想在此处添加一个清晰说明.目的是解码返回的响应.下一步是将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 accomplished. So my syntax is likely off just a little, but this is Pseudocode.

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

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