所以基本上我想将列表反序列化为json对象并将其保存到文件中。 这是我的模型代码。
class NotesList {
final List<Note> notes;
NotesList({
this.notes,
});
factory NotesList.fromJson(List<dynamic> parsedJson) {
List<Note> notes = new List<Note>();
notes = parsedJson.map((i)=>Note.fromJson(i)).toList();
return new NotesList(
notes: notes
);
}
}
class Note {
String title;
String body;
Note({
this.title,
this.body
});
factory Note.fromJson(Map<String, dynamic> json) {
return new Note(
title: json['title'] as String,
body: json['body'] as String,
);
}
}
class Storage {
Future<String> get localPath async {
final dir = await getApplicationDocumentsDirectory();
return dir.path;
}
Future<File> get localFile async {
final path = await localPath;
return File('$path/notes.json');
}
Future<File> writeData(NotesList content) async {
final file = await localFile;
return file.writeAsString("$content");
}
Future<File> clearData() async {
final file = await localFile;
return file.writeAsString("");
}
Future<String> _loadNoteAsset() async {
return await rootBundle.loadString('assets/notes.json');
}
Future<NotesList> loadNotes() async {
String jsonNotes = await _loadNoteAsset();
final jsonResponse = json.decode(jsonNotes);
NotesList notesList = NotesList.fromJson(jsonResponse);
print("First note title: " + notesList.notes[0].title);
return notesList;
}
void writeToFile(String title, String body, int index) async {
print("Writing to file!");
NotesList notesList = await loadNotes();
notesList.notes[index].title = title;
notesList.notes[index].body = body;
writeData(notesList);
print("From writeToFile function $index index title: " + notesList.notes[index].title);
print("From writeToFile function $index index body: " + notesList.notes[index].body);
}
void fileData() async {
try {
final file = await localFile;
String body = await file.readAsString();
print(body);
} catch (e) {
print(e.toString());
}
}
}
我的json的结构如下 [ { “ title”:“标题1”, “ body”:“贪婪的身体” }, { “ title”:“标题2”, “ body”:“贪婪的身体” }, { “ title”:“标题3”, “ body”:“贪婪的身体” }, { “ title”:“标题4”, “ body”:“贪婪的身体” } ]
我要反序列化列表的主要功能是在Storage类的writeToFile函数中。
答案 0 :(得分:-1)
例如,您可以使用dart convert。
您的writeData方法可能如下所示。关于我还将content
的{{1}}参数的类型从writeData
更改为NotesList
List
...
import 'dart:convert';