Home > Software design >  Flutter freezed convert List to json
Flutter freezed convert List to json

Time:10-29

this is my two freezed class which i want to make a simple json from ContactsData

@freezed
class ContactsData with _$ContactsData {
  const factory ContactsData({
    String? displayName,
    String? givenName,
    String? familyName,
    String? company,
    String? jobTitle,
    List<ContactPhone>? phones,
  }) = _ContactsData;

  factory ContactsData.fromJson(Map<String, dynamic> json) => _$ContactsDataFromJson(json);
}

@freezed
class ContactPhone with _$ContactPhone {
  const factory ContactPhone({
    String? label,
    String? value,
  }) = _ContactPhone;

  factory ContactPhone.fromJson(Map<String, dynamic> json) => _$ContactPhoneFromJson(json);
}

i added some data into allContacts by this code:

late List<ContactsData> allContacts=[];

contacts?.forEach((c) {
  List<ContactPhone> phones=[];
  c.phones!.forEach((f) =>phones.add(ContactPhone(label: f.label,value: f.value)));
  allContacts.add(
    ContactsData(
      displayName:c.displayName,
      givenName: c.givenName,
      familyName: c.familyName,
      company: c.company,
      jobTitle: c.jobTitle,
      phones: phones,
    )
  );
});

now how can i convert allContacts to json like with this code:

allContacts.toJson();

build.yaml:

targets:
  $default:
    builders:
      json_serializable:
        options:
          explicit_to_json: true

CodePudding user response:

allContacts is just a regular List.

Either:

  1. make it an object (possibly even a freezed object) similar to ContactsData and call it something like ContactsCollection or something better... and add toJson method to it.

Or

  1. Do something like jsonEncode(allContacts.map((c) => c.toJson()).toList())
  • Related