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
jsonDatais 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 tojsonParser.parse(). - Double-check key names in your JSON—they're case-sensitive, so typos will break your lookup.
内容的提问来源于stack exchange,提问作者kjeraska

