在dart中解析对象(未处理的异常:类型'_InternalLinkedHashMap <dynamic,dynamic>'不是类型'Map <String,dynamic>'的子类型)

时间:2020-09-16 20:16:49

标签: json list flutter dart google-cloud-firestore

当我尝试将json转换为对象时,出现此错误:

Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'

只有当我尝试转换对象类型的ListChat对象时,这种情况才会发生, 这是对象的类和函数fromJson。 我不知道转换有什么问题。

class Project {
  String projectID;
  String projectName;
  String image;
  String joiningLink;
  bool isJoiningLinkEnabled;
  String pinnedMessage;
  Chat chat;
  List<Event> event;
  List<Member> members;
  List<String> membersIDs;
  List<Task> task;

  Project(
      {this.projectID,
        this.projectName,
        this.image,
        this.joiningLink,
        this.isJoiningLinkEnabled,
        this.pinnedMessage,
        this.chat,
        this.event,
        this.members,
        this.membersIDs,
        this.task});

  // Exception shows here
  Project.fromJson(Map<String, dynamic> json) {
    projectID = json['projectID'];
    projectName = json['projectName'];
    image = json['image'];
    joiningLink = json['joiningLink'];
    isJoiningLinkEnabled = json['isJoiningLinkEnabled'];
    pinnedMessage = json['pinnedMessage'];
    if (json['event'] != null) {
      event = new List<Event>();
      json['event'].forEach((v) {
        event.add(new Event.fromJson(v));
      });
    }
    chat = json['chat'] != null ? new Chat.fromJson(json['chat']) : null;
    if (json['members'] != null) {
      members = new List<Member>();
      json['members'].forEach((v) {
        members.add(new Member.fromJson(v));
      });
    }
    membersIDs = List.of(json['membersIDs'].cast<String>());
    if (json['Task'] != null) {
      task = new List<Task>();
      json['Task'].forEach((v) {
        task.add(new Task.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['projectID'] = this.projectID;
    data['projectName'] = this.projectName;
    data['image'] = this.image;
    data['joiningLink'] = this.joiningLink;
    data['isJoiningLinkEnabled'] = this.isJoiningLinkEnabled;
    data['pinnedMessage'] = this.pinnedMessage;
    if (this.chat != null) {
      data['chat'] = this.chat.toJson();
    }
    if (this.event != null) {
      data['event'] = this.event.map((v) => v.toJson()).toList();
    }
    if (this.members != null) {
      data['members'] = this.members.map((v) => v.toJson()).toList();
    }
    data['membersIDs'] = this.membersIDs;
    if (this.task != null) {
      data['Task'] = this.task.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

1 个答案:

答案 0 :(得分:1)

似乎解码器(也许是json.decoder)会解码地图中的所有对象,但是聊天是以无法将键解释为String的方式进行解码的,因此它使用了{{1 }},您可以尝试创建一个将动态转换为String的Map并将其作为<dynamic, dynamic>的参数传递(我认为它接受Map 作为参数,这就是为什么它会触发错误)

Chat.fromJson()