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

Android Studio中手机内部存储JSON文件的创建读写与空指针问题

看起来你已经在尝试构建嵌套JSON并处理文件读写了,不过遇到了空指针和文件检查的问题,我来帮你梳理出完整的解决方案:

一、先搞定嵌套JSON的结构构建

你原来的代码只直接把component放在根JSON里,要实现目标结构,需要先创建configX对应的JSONObject,再把component放入其中,最后把configX对象放到根JSON中。示例代码如下:

// 构建单个config对象
JSONObject config1 = new JSONObject();
try {
    config1.put("component1", "url1");
    config1.put("component2", "url2");
    config1.put("component3", "url3");

    // 构建根JSON对象
    JSONObject rootJson = new JSONObject();
    rootJson.put("config1", config1);
    // 如果需要添加config2,同理
    JSONObject config2 = new JSONObject();
    config2.put("component1", "url4");
    rootJson.put("config2", config2);

    // 后续写入文件的逻辑...
} catch (JSONException e) {
    e.printStackTrace();
}

二、安全检查文件&避免空指针的核心逻辑

你的空指针异常出在data.getMap().containsKey("config1"),本质是data.getMap()可能为null,而且其实我们不需要转成Map,直接用JSONObject自带的has()方法更安全。

完整的流程应该是:

  1. 检查目标JSON文件是否存在
  2. 若存在:读取文件内容并解析为JSONObject,检查是否包含config1,不包含则添加
  3. 若不存在:直接创建包含config1的新JSON文件
  4. 所有对象操作前先判空,避免空指针

三、完整的保存/更新代码示例

public void saveOrUpdateConfig() {
    String fileName = "jsonfile";
    File jsonFile = new File(getFilesDir(), fileName);
    JSONObject rootJson = new JSONObject();

    try {
        // 检查文件是否存在
        if (jsonFile.exists()) {
            // 读取已有文件内容
            FileInputStream fis = openFileInput(fileName);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            String existingJsonStr = new String(buffer);
            // 解析为JSONObject,这里要判空避免解析失败
            if (!TextUtils.isEmpty(existingJsonStr)) {
                rootJson = new JSONObject(existingJsonStr);
            }
        }

        // 检查config1是否存在,不存在则添加
        if (!rootJson.has("config1")) {
            JSONObject config1 = new JSONObject();
            config1.put("component1", "default_url1");
            config1.put("component2", "default_url2");
            config1.put("component3", "default_url3");
            rootJson.put("config1", config1);
        }

        // 将更新后的JSON写入文件
        FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
        fos.write(rootJson.toString().getBytes());
        fos.close();
        Log.d("JSON", "保存/更新成功:" + rootJson.toString());

    } catch (IOException | JSONException e) {
        Log.e("JSON_ERROR", "操作失败", e);
        e.printStackTrace();
    }
}

四、安全读取JSON数据的代码示例

读取时同样要层层判空,避免空指针:

public void readConfigData() {
    String fileName = "jsonfile";
    File jsonFile = new File(getFilesDir(), fileName);

    try {
        if (jsonFile.exists()) {
            FileInputStream fis = openFileInput(fileName);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            String jsonStr = new String(buffer);

            if (!TextUtils.isEmpty(jsonStr)) {
                JSONObject rootJson = new JSONObject(jsonStr);
                // 先检查config1是否存在
                if (rootJson.has("config1")) {
                    JSONObject config1 = rootJson.getJSONObject("config1");
                    // 读取component时也可以先检查是否存在
                    String component1 = config1.optString("component1", "default_value");
                    String component2 = config1.optString("component2", "default_value");
                    Log.d("JSON_READ", "component1: " + component1 + ", component2: " + component2);
                } else {
                    Log.d("JSON_READ", "config1不存在");
                }
            }
        } else {
            Log.d("JSON_READ", "文件不存在");
        }
    } catch (IOException | JSONException e) {
        Log.e("JSON_ERROR", "读取失败", e);
        e.printStackTrace();
    }
}

关键注意点

  • 避免空指针:使用JSONObject.has()检查key是否存在,用optString()/optJSONObject()代替getString()/getJSONObject(),后者在key不存在时会抛出异常,前者会返回默认值或null
  • 文件检查:用getFilesDir()获取内部存储的私有目录,确保文件路径正确
  • 异常处理:不要只打印堆栈,添加日志便于排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 07:08:12