【发布时间】:2018-12-05 19:52:53
【问题描述】:
我正在使用 dart 包 json_serializable 进行 json 序列化。查看颤振文档,它显示了如何反序列化单个对象,如下所示:
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 不够熟悉,无法弄清楚如何对项目列表而不是单个实例执行相同操作。
【问题讨论】:
-
好吧,它解码响应正文,并将其传递给本质上的 POST 构造函数。如果你解码的 JSON 是一个数组,你需要循环它并构建一个 Posts 数组。这就是你要问的吗?检查解码的类型以确保它是可迭代的,然后执行类似于:
List<Post> posts = json.decode(response.body).map((Map m)=> Json.fromJson(m)).toList();