I am using the dart package json_serializable for json serialization. Looking at the flutter documentation it shows how to deserialize a single object as follow:
Future<Post> fetchPost() async { final response = await http.get('https://jsonplaceholder.typicode.com/posts/1'); if (response.statusCode == 200) { // If the call to the server was successful, parse the JSON return Post.fromJson(json.decode(response.body)); } else { // If that call was not successful, throw an error. throw Exception('Failed to load post'); } }
However, I am not familiar enough with dart to figure out how to do the same for a list of items instead of a single instance.
We have 3 steps to convert an Object/List to JSON string: create the class. create toJson() method which returns a JSON object that has key/value pairs corresponding to all fields of the class. get JSON string from JSON object/List using jsonEncode() function.
Well, your service would handle either the response body being a map, or a list of maps accordingly. Based on the code you have, you are accounting for 1 item.
If the response body is iterable, then you need to parse and walk accordingly, if I am understanding your question correctly.
Example:
Iterable l = json.decode(response.body); List<Post> posts = List<Post>.from(l.map((model)=> Post.fromJson(model)));
where the post is a LIST of posts.
EDIT: I wanted to add a note of clarity here. The purpose here is that you decode the response returned. The next step, is to turn that iterable of JSON objects into an instance of your object. This is done by creating fromJson methods in your class to properly take JSON and implement it accordingly. Below is a sample implementation.
class Post { // Other functions and properties relevant to the class // ...... /// Json is a Map<dynamic,dynamic> if i recall correctly. static fromJson(json): Post { Post p = new Post() p.name = ... return p } }
I am a bit abstracted from Dart these days in favor of a better utility for the tasks needing to be accomplished. So my syntax is likely off just a little, but this is Pseudocode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With