How to Deserialize a list of objects from json in Flutter?

· 3 min read
How to Deserialize a list of objects from json in flutter
How to Deserialize a list of objects from json in flutter

When looking at the flutter official documentation it shows how to deserialize a single object. So in this article, we will go through How to deserialize a list of objects from JSON in Flutter. 

How to Deserialize a list of objects from JSON in Flutter?

When using the dart package json_serializable for JSON serialization. To deserialize a list of objects from JSON in flutter follows the below steps:

1-> create a model class and click here to convert JSON to dart.

2-> create a response like loginResponce=LoginResponce.fromJson(json.decode(response.body));

3 -> Now you get your data in instence of model (as loginResponce ).

Another example on JSON Parsing for further clarification.

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

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

  }

You can also do it like below:

List< Item > itemsList= List< Item >.from(parsedListJson.map((i) => Item.fromJson(i)));

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

Conclusion:

Thanks for Reading! Hope you enjoyed it. Let us know in the comments right below, What methods you have used for this problem.

So in this article, we have been through how to deserialize a list of objects from JSON in Flutter.

Keep Learning !!! Keep Fluttering !!! Stay Connected.

Lots of amazing content coming up your way!!

Still, need Support for Flutter Development? Do let us know. We would love to assist you.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply