首页 > 解决方案 > Flutter 如何将 List 与 JSON 相互转换

问题描述

我使用两个函数将两个字符串变量转换为 JSON 和 JSON。

String toJson() {
  Map<String,dynamic> map = {'name': name,'count':checkListCount,'description':description,};
  return jsonEncode(map)
}

fromJson(String context){
  Map<String,dynamic> map = jsonDecode(contents)
  name = map['name'];
  description = map['description'];
  return '0';
}

我如何使用它来隐藏列表?有我的清单

List<CheckListPoint> checkListPoints = [];

CheckListPoint{
  bool correctly = false;
  bool passed = false;
  String requirement = '';
}

我在 CheckListPoint 中拥有的变量将由用户稍后在应用程序中更改。

标签: flutterdart

解决方案


从 firebase 获取消息时,我做了一件非常相似的事情。这与从 JSON 解析相同,因为这两个值都是动态的。

在这里,我将DataSnapshot转换为List

Future<List<Message>> getMessages(DataSnapshot snapshot) async {
    List<Message> msgs = List.empty(growable: true);
    if(snapshot.value != null) {
      Map<dynamic, dynamic> messages = snapshot.value;
      messages.forEach((key, value) {
        msgs.add(Message.fromFirebase(value));
      });
    }
    return msgs;
 }

这是消息类:

class Message {
  String message;
  String senderId;
  int time;

  Message.fromFirebase(Map<dynamic, dynamic> json) :
      message = json["message"],
      senderId = json["senderId"],
      time = json["time"];
}

推荐阅读