Reputation: 450
Right now i am trying to parse a complex json output from my api. Before using pagination it was fine (i will give the code below) but right now i am using pagination and i can't figure out how to parse this code.
Json Output
{
"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":"[email protected]"}{"id":"7463e530-368e-45c6-97ec-0599018a27df","email":"[email protected]"}]
}
Before pagination it was like this:
[{"id":"6463e530-368e-45c6-97ec-0599018a27df","email":"[email protected]"},{"id":"7463e530-368e-45c6-97ec-0599018a27df","email":"[email protected]"}]
What i need to do is parse the post model inside "results". Here is my code
Json Parse Code
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;
}
Upvotes: 1
Views: 103
Reputation: 631
this is how you fetch data.
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;
}
}
Upvotes: 2