How to Deserialize a list of objects from json in flutter

Solution 1:

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.

Solution 2:

I always use this way with no problem;

List<MyModel> myModels;
var response = await http.get("myUrl");

myModels=(json.decode(response.body) as List).map((i) =>
              MyModel.fromJson(i)).toList();

Solution 3:

You can also Do it like

  List<dynamic> parsedListJson = jsonDecode("your json string");
  List<Item> itemsList = List<Item>.from(parsedListJson.map((i) => Item.fromJson(i)));

where Item is your custom class, where you implemented toJson and fromJson.

Solution 4:

Just another example on JSON Parsing for further clarification.

Let say we want to parse items array in our JSON Object.

factory YoutubeResponse.fromJSON(Map<String, dynamic> YoutubeResponseJson) 
 {

// Below 2 line code is parsing JSON Array of items in our JSON Object (YouttubeResponse)


var list = YoutubeResponseJson['items'] as List;
List<Item> itemsList = list.map((i) => Item.fromJSON(i)).toList();

return new YoutubeResponse(
    kind: YoutubeResponseJson['kind'],
    etag: YoutubeResponseJson['etag'],
    nextPageToken: YoutubeResponseJson['nextPageToken'],
    regionCode: YoutubeResponseJson['regionCode'],
    mPageInfo: pageInfo.fromJSON(YoutubeResponseJson['pageInfo']),

    // Here we are returning parsed JSON Array.

    items: itemsList);

  }