【发布时间】:2019-11-19 16:27:18
【问题描述】:
我从 editText 获取输入并尝试将其文本写入 json 文件。当我执行代码时,它可以正常工作。但是当我再次尝试读取 json 文件时,它没有以前写入的对象。
我尝试过使用不同的编写器,例如 BufferedWriter、FileWriter。它们都不起作用。
这是 writeToJsonFile 方法
void writeJsonFile(TextView textView) {
String json;
try {
InputStream is = context.getAssets().open("chores.json");
int size = is.available();
byte[] buffer = new byte[size];
if (is.read(buffer) == -1) {
throw new EOFException();
}
is.close();
json = new String(buffer, StandardCharsets.UTF_8);
JSONObject obj = new JSONObject(json);
JSONObject m_jArray = obj.getJSONObject("chores");
JSONArray jsonArray = m_jArray.getJSONArray(title);
JSONObject new_jobj = new JSONObject();
new_jobj.put("task", textView.getText());
new_jobj.put("isCompleted", false);
jsonArray.put(new_jobj);
File file = new File(context.getExternalFilesDir("/assets"), "chores.json");
writeJsonFile(file, obj);
Log.i("Done => ", "Written to file");
} catch (EOFException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
这个函数接受一个文件和一个json对象并将json对象写入文件
public static void writeJsonFile(File file, JSONObject json) throws IOException {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(json.toString());
if (fileWriter != null) {
fileWriter.close();
}
}
我希望它将json字符串写入文件,但是下次我用InputStream再次读取文件时,它不会显示之前添加的Object。
预期的家务.json
{
"chores": {
"Daily": [
{
"task": "Task 1",
"isCompleted": false
}
],
"Weekly": [
],
"Monthly": [
],
"Custom": [
]
}
}
生成的 json
{
"chores": {
"Daily": [
],
"Weekly": [
],
"Monthly": [
],
"Custom": [
]
}
}
【问题讨论】:
-
您必须将 jsonArray 写入 JSONObject,然后将该 JSONObject 写入文件。
-
@SriAji JSON 数组已经在 json 对象中。我还需要把它放在obj中吗?它不会向对象添加一个新数组吗?我想将对象添加到现有数组中。
-
你没有添加 'jsonArray' 到任何东西。
-
您确定它没有出现任何异常吗?你能检查你的logcat并在这里报告吗?我认为它引发了一个异常,该异常被您的 catch 块捕获并且没有使应用程序崩溃。
-
可能是你正在创建新文件,检查文件路径
标签: java android json file filewriter