I am writing an object to a JSON file locally. When I try and read it, I receive this error:
E/flutter ( 7621): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 2)
E/flutter ( 7621): {players: [{id: Nebula, setCount: 0 - 0, characters: {char1: ice_climbers, char2: captain_falcon}, notes: }]}
E/flutter ( 7621): ^
I understand that the reason I'm getting this error is because that player is not between quotes. i.e. "player". I do not know how to write the object as a JSON with the quotes included.
This code was generated by the JsonSerializableGenerator
PlayerList.toJson:
PlayerList _$PlayerListFromJson(Map<String, dynamic> json) {
return PlayerList(
(json['players'] as List)
?.map((e) =>
e == null ? null : Player.fromJson(e as Map<String, dynamic>))
?.toList(),
);
}
Map<String, dynamic> _$PlayerListToJson(PlayerList instance) =>
<String, dynamic>{
'players': instance.players?.map((e) => e?.toJson())?.toList(),
};
This is how I read and write the file:
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/playerData.json');
}
Future<File> writePlayerData(PlayerList playerList) async {
final file = await _localFile;
return file.writeAsString(playerList.toJson().toString());
}
Future<PlayerList> readPlayerData () async {
try {
final file = await _localFile;
String contents = await file.readAsString();
final jsonResponse = jsonDecode(contents);
PlayerList playerList = PlayerList.fromJson(jsonResponse);
return playerList;
} catch (e) {
print(e);
return getPlayerList(); //just loads a placeholder json in the assets folder;
}
}
What I want the JSON to be formatted as:
{
"players": [
{
"id": "Filler Character",
"setCount": "0 - 0",
"characters": {
"char1": "",
"char2": ""
},
"notes": "Filler Character"
}
]
}
What the program saves:
{players: [{id: Nebula, setCount: 0 - 0, characters: {char1: ice_climbers, char2: captain_falcon}, notes: }]}
Do I need to manually add the quotes back into the JSON, or is there a different way of saving them?