TransWikia.com

How to Deserialize a list of objects from json in flutter

Stack Overflow Asked by Gainz on January 28, 2021

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.

8 Answers

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.

Correct answer by Fallenreaper on January 28, 2021

This is my Model class -

  class SuggestedMovie {
  String title;
  String genres;
  int movieId;
  SuggestedMovie({this.title, this.genres, this.movieId});
  factory SuggestedMovie.fromJson(Map<dynamic, dynamic> parsedJson) {
    return SuggestedMovie(
      movieId: parsedJson['movieId'],
      title: parsedJson['title'] as String,
      genres: parsedJson['genres'] as String,
    );
  }
}

The one below is the code for Deserializing the JSON response into List

 suggestedMovie = (json.decode(jsonResponse.data) as List)
      .map((i) => SuggestedMovie.fromJson(i))
      .toList();

Answered by Akhil Shukla on January 28, 2021

For example, every item in the array is a JSON object.

{
  "tags": [
    {
      "name": "dart",
      "quantity": 12
    },
    {
      "name": "flutter",
      "quantity": 25
    },
    {
      "name": "json",
      "quantity": 8
    }
  ]
}

We will need a class that represents the Tag item. So we create Tag class with 2 fields like this.

class Tag {
  String name;
  int quantity;

  Tag(this.name, this.quantity);

  factory Tag.fromJson(dynamic json) {
    return Tag(json['name'] as String, json['quantity'] as int);
  }

  @override
  String toString() {
    return '{ ${this.name}, ${this.quantity} }';
  }
}

The method factory Tag.fromJson(dynamic json) will parse a dynamic object into a Tag object. We will need it in the main() function, at the mapping step.

import 'dart:convert';

main() {
  String arrayObjsText =
      '{"tags": [{"name": "dart", "quantity": 12}, {"name": "flutter", "quantity": 25}, {"name": "json", "quantity": 8}]}';

  var tagObjsJson = jsonDecode(arrayObjsText)['tags'] as List;
  List<Tag> tagObjs = tagObjsJson.map((tagJson) => Tag.fromJson(tagJson)).toList();

  print(tagObjs);
}

Let me explain the code above. It’s simple. – jsonDecode() convert the 'tags' JSON object into a dynamic object. Then we use brackets ['tags'] to get JSON array inside it. – as List returns a List<dynamic> that we will use map() to change every dynamic item of the List into Tag object. – Finally, .toList() convert the Iterable result above into List<Tag> object.

Now, if we run the code, the result will be like this.

[{ dart, 12 }, { flutter, 25 }, { json, 8 }]

Answered by Paresh Mangukiya on January 28, 2021

follow this step
step 1-> create model class (name as LoginResponce ) click here to convert json to dart .
step 2-> LoginResponce loginResponce=LoginResponce.fromJson(json.decode(response.body));

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

Answered by vinod yadav on January 28, 2021

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

Answered by Bilal Şimşek on January 28, 2021

You can also Do it like

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

Answered by Aks on January 28, 2021

First, create a class that matches your json data, in my case, I create (generate) class named Img:

import 'dart:convert';

Img imgFromJson(String str) => Img.fromJson(json.decode(str));
String imgToJson(Img data) => json.encode(data.toJson());

class Img {
    String id;
    String img;
    dynamic decreption;

    Img({
        this.id,
        this.img,
        this.decreption,
    });

    factory Img.fromJson(Map<String, dynamic> json) => Img(
        id: json["id"],
        img: json["img"],
        decreption: json["decreption"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "img": img,
        "decreption": decreption,
    };
}

PS. You can use app.quicktype.io to generate your json data class in dart. then send your post/get to your server:

Future<List<Img>> _getimages() async {
    var response = await http.get("http://192.168.115.2/flutter/get_images.php");
    var rb = response.body;

    // store json data into list
    var list = json.decode(rb) as List;

    // iterate over the list and map each object in list to Img by calling Img.fromJson
    List<Img> imgs = list.map((i)=>Img.fromJson(i)).toList();

    print(imgs.runtimeType); //returns List<Img>
    print(imgs[0].runtimeType); //returns Img

    return imgs;
}

for more info see Parsing complex JSON in Flutter

Answered by Crimin on January 28, 2021

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

  }

Answered by Developine on January 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP