You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中如何仅覆盖JSON对象指定字段而非完全替换文件

解决方案

要实现仅替换JSON中的age字段而不丢失其他数据,核心是先读取原文件的完整JSON内容,修改指定字段后再写回文件,而不是直接创建新的JSONObject覆盖。具体实现步骤及代码如下:

操作步骤

  • 读取现有文件中的完整JSON字符串
  • 将字符串解析为JSONObject对象
  • 修改age字段的值
  • 将修改后的JSONObject重新写入文件

完整代码示例

try {
    // 1. 读取原文件的完整JSON内容
    FileInputStream fis = openFileInput("credentials.txt");
    InputStreamReader isr = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    // 关闭流资源
    br.close();
    isr.close();
    fis.close();

    // 2. 解析字符串为JSONObject
    JSONObject object = new JSONObject(sb.toString());

    // 3. 修改age字段值
    object.put("age", "40");

    // 4. 将完整的修改后JSON写回文件
    String textToSave = object.toString();
    FileOutputStream fileOutputStream = openFileOutput("credentials.txt", MODE_PRIVATE);
    fileOutputStream.write(textToSave.getBytes());
    fileOutputStream.close();

    intentActivity(MainMenu.class);
} catch (FileNotFoundException e) {
    // 处理文件不存在的异常,比如初始化默认JSON结构
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (JSONException e) {
    e.printStackTrace();
}

说明

  • 读取文件时通过BufferedReader逐行读取,确保完整获取原JSON的所有字段数据
  • 基于原JSON解析出的对象修改字段,自然保留了name、gender等原有内容
  • 写回文件时虽仍覆盖原文件,但此时写入的是包含所有字段的完整JSON,不会丢失数据

内容的提问来源于stack exchange,提问作者Hiraeths

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 11:34:58