gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:29:47 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com