json - 我正在将 json 文件中的数据添加到我的列表中,但列表为空
问题描述
我正在从 API 中提取 json 文件并尝试将其添加到列表中,但之后列表为空。
Future<List<Posts>> getPosts() async {
var datas = await http.get(
Uri.parse("https://www.reddit.com/r/TechNewsToday/top.json?count=20"));
var jsonDatas = json.decode(datas.body);
List<Posts> postList = [];
for (int i = 0; i < 7; i++) {
var postJson = jsonDatas["data"]["children"][i];
String subreddit = postJson["data"]["subreddit"];
String title = postJson["data"]["title"];
String thumbnail = postJson["data"]["thumbnail"];
Posts post = Posts(title, thumbnail, subreddit);
postList.add(post);
}
print(postList.length);
return postList;
}
解决方案
所以当我最后尝试这个时,我得到了一个范围错误。不确定 7 在你的 for 循环中来自哪里,但children
在响应中使用长度可能更安全。当我查看 json 响应时,您尝试解析的内容只有 5 个项目。
也许这会改变,但更有理由不在循环中使用固定数字。
这对我有用。
Future<List<Posts>> getPosts() async {
var datas = await http.get(
Uri.parse("https://www.reddit.com/r/TechNewsToday/top.json?count=20"));
var jsonDatas = json.decode(datas.body);
List<Posts> postList = [];
// this is the actual length of what you're trying to parse
final responseLength = jsonDatas["data"]["children"].length as int;
for (int i = 0; i < responseLength; i++) {
var postJson = jsonDatas["data"]["children"][i];
String subreddit = postJson["data"]["subreddit"];
String title = postJson["data"]["title"];
String thumbnail = postJson["data"]["thumbnail"];
Posts post = Posts(title, thumbnail, subreddit);
postList.add(post);
}
print(postList.length);
return postList;
}
推荐阅读
- javascript - 如何让用户看到正在下载的 Azure blob 存储文件,而不是在 Angular 的网络选项卡本身中下载完整的流
- javascript - Webpack:带有样式加载器的捆绑包的 CSS 顺序
- python - 当对实例的所有引用都被销毁(Python)时,在类实例中启动的线程会发生什么?
- javascript - ElasticSearch - [parsing_exception] [multi_match] 格式错误的查询
- python - 在 AWS lambda 中使用 Django
- java - Android Studio 预览与设备不同
- ruby-on-rails - Rails 控制器操作中的查询缓存
- python - Python 中的集合、列表和元组之间的速度测试给出了令人惊讶的结果
- apache-kafka - 如何更改@KafkaStreamsStateStore kafka Stream Cloud 的默认 serdes
- c# - 在模型字段上序列化和反序列化 JSON