【问题标题】:flutter list to nested json manually手动将列表颤动到嵌套的json
【发布时间】:2020-08-06 05:37:43
【问题描述】:

我有一个联系人列表,我想使用 json 字符串将 givenName、familyName 和 displayName 发送到 api..

final contacts =
    (await ContactsService.getContacts(withThumbnails: false)).toList();

我试过但无法创建嵌套数组:

List<dynamic> list = new List<dynamic>();

for (final contact in contacts) {
    list.add(contact.givenName);
}

print(list);

我想要这样的:

[
    {"id":1,"givenName":"Joe","familyname":"Walker"},
    {"id":2,"givenName":"Zoe","familyname":"Sleeper"}
];

【问题讨论】:

  • 你能分享来自 ContactsService 的联系人列表吗?

标签: flutter dart


【解决方案1】:

更新 试试这个

for (final contact in contacts) {
     var json = {'givenName' : contact.givenName, 'familyName': contact.familyName};
     list.add(json);
 }

您的 Contact 类应该有一个 toJson 方法来执行此操作。

class Contact {
   Int id;
  String givenName, familyName;

  Map<String, dynamic> toJson() =>
  {
    'id': id,
    'givenName' : givenName, 
    'familyName': familyName,
  }; 
}

现在你的代码应该可以工作了

List<dynamic> list = new List<dynamic>();

for (final contact in contacts) {
    list.add(contact.toJson());
}

print(list); 

【讨论】:

猜你喜欢
  • 2019-12-07
  • 1970-01-01
  • 2020-11-12
  • 2020-12-03
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
相关资源
最近更新 更多