将Set对象放到JSON中

问题描述 投票:0回答:1

如何将一组对象放到Json中。好像代码根本不好

Future<File> writeBasket(Set<Item> listItems) async {

  final file = await _localFile;
  var jsonString = listItems.map((Item item) {
    return jsonEncode(item);
  });

  return file.writeAsString(jsonString.toString());
}
json flutter
1个回答
0
投票

确保Item具有toJson方法,例如:

class Item {
  String val1;

  Item(this.val1);

  Map<String, dynamic> toJson() => {'val1': val1};
}

与json中的集合最接近的是一个列表,因此在调用json.encode之前将您的集合转换为列表。

  Set<Item> items = Set<Item>()..add(Item('xxx'))..add(Item('yyy'));
  String j = json.encode(items.toList());
  print(j);

打印[{"val1":"xxx"},{"val1":"yyy"}],你可以保存到您的文件。

© www.soinside.com 2019 - 2024. All rights reserved.