json - 我怎样才能正确解析这个json?
问题描述
现在我正在尝试从我的 api 解析一个复杂的 json 输出。在使用分页之前它很好(我将在下面给出代码)但现在我正在使用分页,我无法弄清楚如何解析这段代码。
json输出
{
"count":6,
"next":"http://127.0.0.1:8000/api/articles/?format=json&limit=2&offset=2",
"previous":null,
"results":[{"id":"6463e530-368e-45c6-97ec-0599018a27df","email":"testuser1@gmail.com"}{"id":"7463e530-368e-45c6-97ec-0599018a27df","email":"testuser2@gmail.com"}]
}
分页之前是这样的:
[{"id":"6463e530-368e-45c6-97ec-0599018a27df","email":"testuser1@gmail.com"},{"id":"7463e530-368e-45c6-97ec-0599018a27df","email":"testuser2@gmail.com"}]
我需要做的是解析“结果”中的帖子模型。这是我的代码
Json 解析代码
Future<List<Post>> FetchPosts(http.Client client,categoryconf) async {
List<Post> posts;
final response = await http.get("$SERVER_IP/api/articles/?format=json");
final parsed = jsonDecode(response.body).cast<Map<String, dynamic>>();
posts = parsed.map<Post>((json) => Post.fromJSON(json)).toList();
return posts;
}
解决方案
这就是您获取数据的方式。
class Pagination{
int count;
String next;
String previous;
List<Post> results;
Pagination({this.count,this.next,this.previous,this.results});
factory Pagination.fromJson(Map<String, dynamic> json,) {
if (json["results"] != null) {
var results= json["results"] as List;
List<Post> _results=
results.map((list) => Post.fromJson(list)).toList();
return Pagination(
results: _results,
count: json["count"] as int,
previous: json["previous"] as String
next: json["next"] as String
);
}
return null;
}
}
推荐阅读
- python - 在 MQL5 中接受 Python 生成的套接字的输出
- angular - 如何在Angular 6中用间谍对象替换组件范围的服务?
- c - 如何在缓冲区中打印数据,而不考虑到给定长度之间的零
- javascript - Spip - 将数据从 Javascript 传递到隐藏的输入值
- jquery - 数据表函数“fnDeleteRow”无法删除行
- c# - 如何获取父 Datalist 的行 ID
- vba - 字典后期绑定中的VBA Excel字典
- java - 高速按值搜索 KV 数据库
- c# - 设置按钮变量的列跨度
- google-cloud-dataflow - 如何在运行时使用 ValueProviders 为 SpannerIO 分配表和列?