gpt4 book ai didi

json - 将多行字符串从文本字段保存到 JSON 文件

转载 作者:行者123 更新时间:2023-12-03 03:32:17 28 4
gpt4 key购买 nike

我有一个应用程序,让用户能够在 TextField 中键入和保存文本.如果将文本输入到 TextField 中,它就可以正常工作。是一条连续线。如果用户按下回车键在 TextField 中创建新行它没有正确保存到 JSON 文件。有没有办法从 TextField 保存多行文本?到 JSON 文件?

        Flexible(
child: TextField(
controller: _notesController,
obscureText: false,
maxLines: null,
onChanged: (value) {
// updates playterNotes to the text inputed
playerList.players[index].playerNotes = value;

// updates JSON file
writePlayerData(playerList);
},
style: TextStyle(
color: Color.fromRGBO(255, 174, 3, 1.0),
letterSpacing: 2.0,
fontSize: 14.0,
fontFamily: 'Smash'
),
),
)
编辑:
如果 JSON 文件未正确保存,我会加载占位符 JSON。
这是在最初的“单行”之后打印出来的 JSON
I/flutter ( 4058): {"players":[{"id": "GitHub Test","setCount": "0 - 0","characters": {"char1": "cloud","char2": ""},"notes": "single line"}]} 
这是在“多行”之后打印出来的 JSON
I/flutter ( 4058): {"players":[{"id": "GitHub Test","setCount": "0 - 0","characters": {"char1": "cloud","char2": ""},"notes": "single line
I/flutter ( 4058): multi line"}]}
Test

写入播放器数据:
Future<File> writePlayerData(PlayerList playerList) async {
final file = await _localFile;
return file.writeAsString(PlayerListtoJson(playerList));
}
哪个电话:
String PlayerListtoJson(PlayerList playerList) {
String playerJson = "";

if (playerList.players.length > 0 ) {
playerJson = '{"players":[${playerToJson(playerList.players)}]}';
}
return playerJson;
}

String playerToJson(List<Player> players) {
String playerString = "";

for(int i = 0; i < players.length; i++) {
playerString += '{"id": "${players[i].playerId}",'
'"setCount": "${players[i].playerSetCount}",'
'"characters": ${characterToJson(players[i].playerChars)}'
'"notes": "${players[i].playerNotes}"}';

if (!(i == players.length - 1)) {
playerString += ',';
}
}
return playerString;
}

String characterToJson (Characters characters) {
String playerCharacters = '{"char1": "${characters.char1}",'
'"char2": "${characters.char2}"},';

return playerCharacters;
}
引用 JSON:
{
"players": [
{
"id": "Filler Character",
"setCount": "0 - 0",
"characters": {
"char1": "",
"char2": ""
},
"notes": "Lorem ipsum dolor sit amet, consectetur."
}
]
}

最佳答案

使用 \ 转义新行所以编码器不会在生成的 JSON 中插入新行

String s = 'A\nB\nC';
print('$s');
//A
//B
//C
//escaping the new line with a additional "\"
s = s.split('\n').join('\\n');
//or
//s.replaceAll('\n', '\\n');
print('$s');
//A\nB\nC

关于json - 将多行字符串从文本字段保存到 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63259000/

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