Flutter toJson and fromJson when you have an array

I couldn’t quite figure it out how to get it working when you have an object which has an array of objects in json format. This is what I ended up with. totalItems is a property in the FullWordList class, and this class contains a List of Items, which we declared further down. Both got toJson and fromJson methods which means they can get parsed by json.

And to have the whole object parsed we will first take in the data for FullWordList and inside the fromJson method, we will declare the first property totalItems simply from its value, but the items property will use the general from method from List to create an list with our values, and then we will use the map method to go through each object and use the Item’s fromJson method, and lastly we’ll call toList() to retrieve the List in a List<Item> format.

class FullWordList {
  int totalItems = -1;
  List<Item> items = [];

  FullWordList.fromJson(Map<String, dynamic> json)
      : totalItems = json['totalItems'],
        items = List.from(json['items']).map((e) => Item.fromJson(e)).toList();

  Map<String, dynamic> toJson() =>
      {'totalItems': this.totalItems, 'items': this.items};

class Item {
  String english = "";

  Item.fromJson(Map<String, dynamic> json) : english = json['english'];

  Map<String, dynamic> toJson() => {'english': this.english};

And this is how we could utilize the fromJson method for a FullWordList object using http to retrieve the data.

  Future<FullWordList> getDetails() async {
    var url = Uri.https('mywebsite.com',
        '/api/myapifunction', {"id": "65", "website": "fileidea"});

    // Await the http get response, then decode the json-formatted response.
    var response = await http.get(url);

    if (response.statusCode == 200) {
      var jsonResponse = convert.jsonDecode(response.body);
      FullWordList dataList = FullWordList.fromJson(jsonResponse);
      return dataList;
    } else {
      print('Request failed with status: ${response.statusCode}.');
      return new FullWordList();
0 0 votes
Article rating
Notify of

Inline Feedbacks
View all comments