我怎样才能正确解析这个json?

时间:2021-01-10 10:24:46

标签: json flutter dart

现在我正在尝试解析来自我的 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;
}

1 个答案:

答案 0 :(得分:2)

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

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