Wazza
Wazza

Reputation: 1885

Save object to file as encoded JSON then extract JSON from the file

I'm trying to save an object as JSON in a file that's saved to the cache and the open the file and extract the JSON when I need it again.

My code to save the object as a file with JSON in is:

Future<File> saveJsonFile(FireImage image) async {
  jsonDirectory = '${(await getApplicationDocumentsDirectory()).path}/json_cache/';
  final filePath = '$jsonDirectory${image.name}';
  print("saving json to $filePath");
  return File(filePath)
    ..createSync(recursive: true)
    ..writeAsString(json.encode(image));
}

then to extract the JSON from the file again is:

FireImage fireImageFromEntity(String fileName) {
  File imageFile = File("$jsonDirectory$fileName");
  var imageJson = json.decode(imageFile.toString());
  String name = imageJson["name"];
  DateTime dateTime = new DateTime.fromMillisecondsSinceEpoch(imageJson["dateTime"]);
  int count = imageJson["count"];
  String url = imageJson["url"];

  return new FireImage(name, dateTime, count, url);
}

but when i get to this line var imageJson = json.decode(imageFile.toString()); i get the error FormatException: Unexpected character (at character 1)

Upvotes: 0

Views: 1548

Answers (1)

Richard Heap
Richard Heap

Reputation: 51682

Use readAsString[Sync] to read a file. Try changing

var imageJson = json.decode(imageFile.toString());

to

var imageJson = json.decode(imageFile.readAsStringSync());

Upvotes: 1

Related Questions