【发布时间】:2020-11-08 14:35:54
【问题描述】:
我正在将一个对象写入本地的 JSON 文件。当我尝试阅读它时,我收到此错误:
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): ^
我了解我收到此错误的原因是因为 player 不在引号之间。即“玩家”。我不知道如何将对象写为包含引号的 JSON。
此代码由 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(),
};
这是我读写文件的方式:
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;
}
}
我希望将 JSON 格式化为:
{
"players": [
{
"id": "Filler Character",
"setCount": "0 - 0",
"characters": {
"char1": "",
"char2": ""
},
"notes": "Filler Character"
}
]
}
程序保存的内容:
{players: [{id: Nebula, setCount: 0 - 0, characters: {char1: ice_climbers, char2: captain_falcon}, notes: }]}
我需要手动将引号重新添加到 JSON 中,还是有其他保存方式?
【问题讨论】:
-
字符串内容 = await file.readAsString();最终 jsonResponse = jsonEncode(jsonDecode(contents));
-
只编码你的json
-
我补充说。 jsonEncode(jsonDecode(内容));现在我得到一个错误: PlayerList playerlist = PlayerList.fromJson(jsonResponse);错误是:参数类型“String”不能分配给参数类型“Map
”。 -
jsonDecode(jsonEncode(contents)); ...哦,只是替换