这是我再次提出的另一个一般性问题:
如何在文件系统的一个JSON文件中将Dart / Flutter中的(嵌套)模型结构持久化?
我的模型如下所示:
首先,我的主题模型:
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: List<Topic>.from(
json['topics'].map((topic) => Topic.fromJSON(topic))));
} else {
return null;
}
}
Map<String, dynamic> toJSON() {
return {
'name': name,
'order': order,
'isMajor': isMajor,
'topics': topics,
};
}
}
现在,主题模型:
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: List<Content>.from(
json['contents'].map((content) => Content.fromJSON(content))));
} else {
return null;
}
}
Map<String, dynamic> toJSON() {
return {
'name': name,
'order': order,
'contents': contents,
};
}
}
最后,内容模型:
class Content {
String title;
String body;
int order;
bool isImportant;
Content({this.title, this.body, this.order, this.isImportant});
factory Content.fromJSON(Map<String, dynamic> json) {
if (json != null) {
return Content(
title: json['title'],
body: json['body'],
order: json['order'],
isImportant: json['isImportant']);
} else {
return null;
}
}
Map<String, dynamic> toJSON() {
return {
'title': title,
'body': body,
'order': order,
'isImportant': isImportant,
};
}
}
我感兴趣的是将所有数据编译为JSON-String的方式...好吗?
如果有人有时间和想法,请随时回答!
感谢您的所有努力!
最佳答案
使用jsonEncode
函数将List
或Map
转换为Json字符串:
Map<String, dynamic> json = {
'code' : 241,
};
String jsonString = jsonEncode(json);
在
Subject
类中,json中不支持List<Topic>
类型,因此您需要将其转换为json字符串:Map<String, dynamic> toJSON() {
return {
'name': name,
'order': order,
'isMajor': isMajor,
'topics': topics
.map((topic) => jsonEncode(topic.toJSON()))
.toList(), // topics is now List<String>
};
}
关于json - 如何在本地文件系统中将嵌套Dart模型(和列表)另存为JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60617398/