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

问题描述 投票:1回答:1

所以基本上我想将列表反序列化为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”:“Title 1”,“body”:“Greed body”},{“title”:“Title 2”,“body”:“Greed body”},{“title “:”Title 3“,”body“:”Greed body“},{”title“:”Title 4“,”body“:”Greed body“}]

我想要反序列化列表的主要功能是在Storage类的writeToFile函数中。

json dart flutter
1个回答
-1
投票

例如,您可以使用dart convert

您的writeData方法可能如下所示。我还将contentwriteData参数的类型从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);
}
© www.soinside.com 2019 - 2024. All rights reserved.