gpt4 book ai didi

json - 在 Flutter 中本地写入和读取 JSON 文件不包括引号

转载 作者:行者123 更新时间:2023-12-05 05:00:47 29 4
gpt4 key购买 nike

我正在本地将对象写入 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,或者是否有不同的保存方式?

最佳答案

让,test.json 是您桌面上本地存储的 json 文件。 test.json -

[
{"name":"Ash","age":"22","hobby":"golf"},
{"name":"philip","age":"17","hobby":"fishing"},
{"name":"charles","age":"32","hobby":"drawing"},
]

现在我们要从中读取并写入它。下面的代码完成了任务。 test.dart -

import 'dart:io';
import 'dart:convert';

List<Player> players = [];

void main() async{
print("hello world");
final File file = File('D:/Sadi/.../test.json'); //load the json file
await readPlayerData(file); //read data from json file

Player newPlayer = Player( //add a new item to data list
'Samy Brook',
'31',
'cooking'
);

players.add(newPlayer);

print(players.length);

players //convert list data to json
.map(
(player) => player.toJson(),
)
.toList();

file.writeAsStringSync(json.encode(players)); //write (the whole list) to json file
}

Future<void> readPlayerData (File file) async {


String contents = await file.readAsString();
var jsonResponse = jsonDecode(contents);

for(var p in jsonResponse){

Player player = Player(p['name'],p['age'],p['hobby']);
players.add(player);
}


}

class Player {
late String name;
late String age;
late String hobby;


Player(
this.name,
this.age,
this.hobby,

);

Player.fromJson(Map<String, dynamic> json) {
name = json['name'];
age = json['age'];
hobby = json['hobby'];

}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['age'] = this.age;
data['hobby'] = this.hobby;

return data;
}

}

关于json - 在 Flutter 中本地写入和读取 JSON 文件不包括引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62976813/

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