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

Java项目添加JSON文件遇问题,求代码错误排查与解决方法

问题分析与修复方案

Hey there! Let's break down what's going wrong with your JSON code and fix it up.

核心问题

The get() method of JSONObject (from libraries like json-simple or org.json) doesn't support slash-separated path strings like "users/user/desktop/settingspanel.json". This method only works with direct top-level keys in your JSON structure—you can't jump straight to nested values with a single path string.

假设你的JSON结构

First, let's assume your target JSON data looks something like this (since you didn't share the full structure):

{
  "users": {
    "user": {
      "desktop": {
        "settingspanel.json": "your desired value here"
      }
    }
  }
}

正确的实现方式

方法1:逐层手动解析(适用于基础JSON库)

You need to traverse each nested JSONObject step by step, and add null checks to avoid unexpected NullPointerExceptions:

JSONParser jsonParser = new JSONParser();
JSONObject json = (JSONObject) jsonParser.parse(jsonData);

// Traverse each nested object layer by layer
JSONObject usersObj = (JSONObject) json.get("users");
if (usersObj != null) {
    JSONObject userObj = (JSONObject) usersObj.get("user");
    if (userObj != null) {
        JSONObject desktopObj = (JSONObject) userObj.get("desktop");
        if (desktopObj != null) {
            Object settingValue = desktopObj.get("settingspanel.json");
            System.out.println(settingValue);
        }
    }
}

方法2:使用支持路径访问的JSON库(更简洁)

If you're open to switching libraries, tools like Jackson or JSON-P support path-based lookup out of the box. For example, with Jackson:

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonData);

// Use a slash-separated path to fetch the value directly
JsonNode settingValue = rootNode.at("/users/user/desktop/settingspanel.json");
System.out.println(settingValue.asText());

额外提醒

  • Make sure jsonData is a valid JSON string, not a file path! If you're trying to read a JSON file from disk, you need to first read the file's content into a string before passing it to jsonParser.parse().
  • Double-check key names in your JSON—they're case-sensitive, so typos will break your lookup.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:43:57