如何使用Java(Simple-JSON)从JSONArray获取image值及排障
问题描述
我尝试用Java从以下JSON中获取"image"的值,但遇到了索引越界错误。
Media.json内容
[ { "input": { "contentData": { "image":"Resources/RawImages/Media/InputImage/Media.jpg", "imageMetaData": { "DMLR":"", "imageCaptions":["cool"] } }, "requestMetaData": { "requestId": "12345678", "locale": "en_US" } }, "output": { "isTrue": true, "mMD": { "mcT": 0 }, "result": { "CR": 0.9039373397827148, "category": [ { "Name": "Car", "score": 0.9039373397827148 } ] } } } ]
现有函数代码
public static String getImageFilePath() throws IOException, ParseException { JSONParser readJSON = new JSONParser(); JSONArray image2Json = (JSONArray) readJSON.parse(new FileReader("/Resources/RawImages/" + "Media/InputJson/Media.json") ); JSONObject imgFilePath = (JSONObject) image2Json.get(1); return imgFilePath.toString(); }
错误信息
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266) at java.base/java.util.Objects.checkIndex(Objects.java:361) at java.base/java.util.ArrayList.get(ArrayList.java:427) at com.example.mediaservice.TestUtils.CommonTestUtils.getImageFilePath(CommonTestUtils.java:92) at com.example.mediaservice.TestUtils.CommonTestUtils.imageEncoder(CommonTestUtils.java:63) at com.example.mediaservice.TestUtils.CommonTestUtils.main(CommonTestUtils.java:37) Process finished with exit code 1
问题分析与解决方案
错误原因
- JSON数组仅包含1个元素,索引从0开始,但代码中错误地访问了索引1,直接触发越界异常。
- 现有代码仅获取了外层对象,未逐层解析到
input -> contentData -> image这个目标字段。
修正后的代码
public static String getImageFilePath() throws IOException, ParseException { JSONParser readJSON = new JSONParser(); // 解析JSON文件得到顶层数组 JSONArray image2Json = (JSONArray) readJSON.parse(new FileReader("/Resources/RawImages/" + "Media/InputJson/Media.json")); // 取数组的第一个元素(索引为0) JSONObject outerObj = (JSONObject) image2Json.get(0); // 逐层获取嵌套对象 JSONObject inputObj = (JSONObject) outerObj.get("input"); JSONObject contentDataObj = (JSONObject) inputObj.get("contentData"); // 获取目标image字段的值 String imagePath = (String) contentDataObj.get("image"); return imagePath; }
额外注意事项
- 始终记住JSON数组的索引从0开始,要匹配数组内的实际元素数量
- 多层嵌套的JSON结构必须逐层解析,不能跳过中间节点直接访问深层字段
- 确保文件路径正确,避免因路径错误导致的文件读取异常
内容的提问来源于stack exchange,提问作者gomathi subramanian
相关产品推荐
相关产品推荐

