gpt4 book ai didi

json - _TypeError(类型 'List'不是类型 'Map'的子类型)

转载 作者:行者123 更新时间:2023-12-03 04:55:51 27 4
gpt4 key购买 nike

我正在学习Dart和Flutter。现在,我尝试将JSON作为一种持久性方法。我遇到很多错误,所有错误都与类型和内容有关。这是我遇到的最新错误:_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')

这是类(class):

import './topic.dart';

class Subject {
String name;
int order;
bool isMajor;
List<Topic> topics;

Subject({this.name, this.order, this.isMajor, this.topics});

factory Subject.fromJSON(Map<String, dynamic> json) {
if (json != null) {
return Subject(
name: json['name'],
order: json['order'],
isMajor: json['isMajor'],
topics: [Topic.fromJSON(json['topics'])]);
} else {
return null;
}
}
}

主题类是这样的:
import './content.dart';

class Topic {
String name;
int order;
List<Content> contents;

Topic({this.name, this.order, this.contents});

factory Topic.fromJSON(Map<String, dynamic> json) {
if (json != null) {
return Topic(
name: json['name'],
order: json['order'],
contents: [Content.fromJSON(json['contents'])]);
} else {
return null;
}
}
}

错误出现在这里: [Topic.fromJSON(json['topics'])]

有人可以帮忙吗?谢谢!

最佳答案

主题应该是

topics: List<Topic>.from(json["topics"].map((x) => Topic.fromJson(x))),

因为您没有提供 Content类,所以我假设它具有 nameorder属性
您可以使用 Subject subject = subjectFromJson(jsonString);解析jsonString

完整的相关类(class)
// To parse this JSON data, do
//
// final subject = subjectFromJson(jsonString);

import 'dart:convert';

Subject subjectFromJson(String str) => Subject.fromJson(json.decode(str));

String subjectToJson(Subject data) => json.encode(data.toJson());

class Subject {
String name;
int order;
bool isMajor;
List<Topic> topics;

Subject({
this.name,
this.order,
this.isMajor,
this.topics,
});

factory Subject.fromJson(Map<String, dynamic> json) => Subject(
name: json["name"],
order: json["order"],
isMajor: json["isMajor"],
topics: List<Topic>.from(json["topics"].map((x) => Topic.fromJson(x))),
);

Map<String, dynamic> toJson() => {
"name": name,
"order": order,
"isMajor": isMajor,
"topics": List<dynamic>.from(topics.map((x) => x.toJson())),
};
}

class Topic {
String name;
int order;
List<Content> contents;

Topic({
this.name,
this.order,
this.contents,
});

factory Topic.fromJson(Map<String, dynamic> json) => Topic(
name: json["name"],
order: json["order"],
contents: List<Content>.from(json["contents"].map((x) => Content.fromJson(x))),
);

Map<String, dynamic> toJson() => {
"name": name,
"order": order,
"contents": List<dynamic>.from(contents.map((x) => x.toJson())),
};
}

class Content {
String name;
int order;

Content({
this.name,
this.order,
});

factory Content.fromJson(Map<String, dynamic> json) => Content(
name: json["name"],
order: json["order"],
);

Map<String, dynamic> toJson() => {
"name": name,
"order": order,
};
}

关于json - _TypeError(类型 'List<dynamic>'不是类型 'Map<String, dynamic>'的子类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60606623/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com