首页 > 解决方案 > 我怎样才能正确解析这个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;
}

标签: jsonflutterdart

解决方案


这就是您获取数据的方式。

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;
  }
}

推荐阅读