我正在学习Dart和Flutter。现在,我尝试将JSON作为一种持久性方法。我遇到很多错误,所有错误都与类型和内容有关。这是我遇到的最新错误:_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')
。
这是课程:
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'])]
。
有人可以帮忙吗?谢谢!
答案 0 :(得分:1)
主题应该是
topics: List<Topic>.from(json["topics"].map((x) => Topic.fromJson(x))),
因为您没有提供Content
类,所以我假设它具有name
和order
属性
您可以使用Subject subject = subjectFromJson(jsonString);
来解析jsonString
完整的相关课程
// 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,
};
}