Flutter中如何将Freezed生成的ContactsData列表转换为JSON
如何将List转换为JSON?
问题背景
我定义了两个Freezed类ContactsData和ContactPhone,并将数据填充到List<ContactsData>类型的allContacts列表中,希望实现类似allContacts.toJson()的方式将列表转换为JSON:
@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); }
填充数据的代码:
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, ) ); });
build.yaml配置:
targets: $default: builders: json_serializable: options: explicit_to_json: true
解决方案
Dart的List本身没有内置toJson方法,但Freezed已为单个ContactsData实例生成了该方法,再加上你开启的explicit_to_json: true配置,内部的ContactPhone列表会被自动处理,你可以通过以下两种方式实现需求:
1. 直接转换(快速实现)
用map遍历列表,将每个ContactsData转为JSON对象,再通过jsonEncode生成最终的JSON字符串:
import 'dart:convert'; // 生成JSON字符串 String contactsJson = jsonEncode(allContacts.map((contact) => contact.toJson()).toList());
2. 扩展List方法(优雅复用)
给List<ContactsData>添加扩展方法,让它支持类似toJson()的调用方式:
import 'dart:convert'; extension ContactsListExtension on List<ContactsData> { // 转换为JSON对象列表 List<Map<String, dynamic>> toJson() { return map((contact) => contact.toJson()).toList(); } // 直接生成JSON字符串 String toJsonString() { return jsonEncode(toJson()); } } // 使用示例 List<Map<String, dynamic>> jsonObjectList = allContacts.toJson(); String jsonString = allContacts.toJsonString();
内容的提问来源于stack exchange,提问作者DolDurma
相关产品推荐
相关产品推荐

