這是我的兩freezed門課,我想從中做一個簡單json的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);
}
allContacts我通過這段代碼添加了一些資料:
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,
)
);
});
json現在我如何使用此代碼將 allContacts 轉換為like:
allContacts.toJson();
build.yaml:
targets:
$default:
builders:
json_serializable:
options:
explicit_to_json: true
uj5u.com熱心網友回復:
allContacts 只是一個常規串列。
任何一個:
- 使其成為類似于 ContactsData 的物件(甚至可能是凍結的物件),并將其稱為 ContactsCollection 或更好的名稱……并向其添加 toJson 方法。
或者
- 做類似的事情
jsonEncode(allContacts.map((c) => c.toJson()).toList())
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/523020.html
標籤:json扑颤动冻结
