Home > Software design >  How to convert lists to json in model in flutter?
How to convert lists to json in model in flutter?

Time:09-29

I have a model through which I receive data from the server. I do everything through the fromJson method, as it should be, but I ran into a problem that I can’t convert some data back to toJson. I have lists that I get but how to convert them back to json with this there are difficulties. Can you tell me how to correctly write the data in the toJson() method so that they are converted?

 class PublicChargingStationModel {
      final int id;
      String name;
      List<AmenitiesModel>? amenities;
      List<ScheduleModel>? schedules;
      List<PublicChargingDeviceModel>? devices;
      List<PhotoModel>? photos;
      String? picture;
      User? user;
    
      PublicChargingStationModel({
        required this.id,
        required this.name,
        this.amenities,
        this.devices,
        this.schedules,
        this.photos,
        this.user,
        this.picture,
      });
    
      factory PublicChargingStationModel.fromJson(Map<String, dynamic> json) =>
          PublicChargingStationModel(
              id: json['id'],
              name: json['name'],],
              picture: json['pi cture'] != null ? json['picture']['url'] : null,
              amenities: json['amenities'] != null
                  ? List<AmenitiesModel>.from(
                      json['amenities'].map(
                        (item) => AmenitiesModel.fromJson(item),
                      ),
                    ).toList()
                  : null,
              user: json['user'] != null ? User.fromJson(json['user']) : null,
              devices: json['devices'] != null
                  ? List<PublicChargingDeviceModel>.from(
                      json['devices'].map(
                        (item) => PublicChargingDeviceModel.fromJson(item),
                      ),
                    ).toList()
                  : null,
              photos: json['gallery'] != null
                  ? List<PhotoModel>.from(
                      json['gallery'].map(
                        (item) => PhotoModel.fromJson(item),
                      ),
                    ).toList()
                  : null);
    
      Map<String, dynamic> toJson() {
        return {
          'blocked': blocked,
          'latitude': latitude,
          'longitude': longitude,
          'name': name,
          'id': id,
          'isFavorite': isFavorite,
          'public': public,
          'status': status,
          'is_open': isOpen,
          'is_free': isFree,
          'country': country,
          'city': city,
          'address': address,
          'zip': zip,
          'remarks': remarks,
          'manual_order_confirmation': isManualOrderConfirmation,
          'picture': picture,
          'formatted_parking_cost_per_hour': formattedParkingCostPerHour,
          'operator': operator,
          'amenities': amenities,
          'user': user,
          'devices': devices,
          'gallery': photos,
    };

  }

CodePudding user response:

You have to map your List<AmenitiesModel> to List<Map<String, dynamic>> by calling toJson of AmenitiesModel.

Add this code in your PublicChargingStationModel toJson()

'amenities': amenities?.map((e) => e.toJson()).toList(),

Do this same for other lists.

Also, I suggest you to use automatic code generation instead of manually creating fromJson and toJson

https://docs.flutter.dev/development/data-and-backend/json#use-code-generation-for-medium-to-large-projects

https://pub.dev/packages/json_serializable

CodePudding user response:

Let say we have List Like this:

list<PublicChargingStationModel> _list = [...];

you can convert it to json like this:

var yourResult = {
   'data': _list.map((e) => e.toJson()).toList()
}

Note that before use this in your api try this:

import 'dart:convert';

jsonEncode(yourResult);
  • Related