- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
所以基本上我想将列表反序列化为 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 函数。
最佳答案
您可以使用 dart convert例如。
您的 writeData 方法可能如下所示。请注意,我还将 writeData
的 content
参数的类型从 NotesList
更改为 List
import 'dart:convert';
...
Future<File> writeData(List content) async {
final file = await localFile;
jsonText = jsonEncode(content.notes);
print("This text will be wirtten to file: " + jsonText);
return file.writeAsString(jsonText);
}
关于json - 如何将 Dart 列表反序列化为 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54845972/
出于好奇,我尝试了一些原型(prototype)制作,但似乎只允许在第一个位置使用子例程的原型(prototype) &。 当我写作时 sub test (&$$) { do_somethin
我需要开发一个类似于 Android Play 商店应用程序或类似 this app 的应用程序.我阅读了很多教程,发现几乎每个教程都有与 this one 类似的例子。 . 我已经开始使用我的应用程
考虑一个表示“事件之间的时间”的列: (5, 40, 3, 6, 0, 9, 0, 4, 5, 18, 2, 4, 3, 2) 我想将这些分组到 30 个桶中,但桶会重置。期望的结果: (0, 1,
我是一名优秀的程序员,十分优秀!