gpt4 book ai didi

json - 如何将 Dart 列表反序列化为 json 对象?

转载 作者:IT王子 更新时间:2023-10-29 06:46:28 25 4
gpt4 key购买 nike

所以基本上我想将列表反序列化为 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 方法可能如下所示。请注意,我还将 writeDatacontent 参数的类型从 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/

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