本文介绍了如何在JSON文件抖动中编辑(更新)数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将特定值更新为外部存储中的JSON文件.
I am trying to update specific value to a JSON File in external Storage.
虽然我能够写入文件,但是它用单个数据替换了整个JSON文件.
Though I am able to write to the file but It is replacing the whole JSON File with the single data.
//这是用单个值替换整个文档
// This one is Replacing the whole document with single value
Future setBookmark(int questionId, String isBookmark) async {
Map<String, dynamic> content = {questionId.toString(): isBookmark};
var dir = await getExternalStorageDirectory();
var testdir = new Io.Directory('${dir.path}/BCS/bcs.json');
File jsonFile = File(dir.path + "/BCS/" + "bcs.json");
Map<String, dynamic> jsonFileContent =
json.decode(jsonFile.readAsStringSync());
jsonFileContent.addAll(content);
jsonFile.writeAsStringSync(json.encode(_listQuestions
.firstWhere((question) => question.id == questionId)
.bookmark = isBookmark));
}
//这是暂时更改值,但未写入文件
//this is changing the value temporarily but not writing to the file
Future setBookmark(int questionId, String isBookmark) async {
_listQuestions
.firstWhere((question) => question.id == questionId)
.bookmark = isBookmark;
}
推荐答案
您需要编写整个问题列表.将其分为两个语句
You need to write the whole question list. Break it into two statements
Future setBookmark(int questionId, String isBookmark) async {
// update the list
_listQuestions
.firstWhere((question) => question.id == questionId)
.bookmark = isBookmark;
// and write it
jsonFile.writeAsStringSync(json.encode(_listQuestions));
}
这篇关于如何在JSON文件抖动中编辑(更新)数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!