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

使用simple-json解析嵌套JSON数组时获取目标值遇阻

用simple-json提取嵌套JSON值的解决方案

嘿,我来帮你搞定这个问题!先看看你的JSON结构——这是个嵌套层级有点多的结构,咱们一步步拆解就能拿到想要的值。

先理清你的JSON结构

你的JSON是个顶层数组,里面包含1个对象;这个对象的键是"BUTT LIFT (BRIDGE)",对应的值又是一个数组;而这个子数组里的第一个对象,就是存储所有目标字段(比如Main Muscle Worked、Force)的地方:

[
{
"BUTT LIFT (BRIDGE)": [
{
"Main Muscle Worked": "Glutes",
"Sport": "No",
"Force": "Push",
"Level": "Beginner",
// 其他字段...
}
]
}
]

用simple-json提取值的代码示例

下面是Java环境下的完整代码(假设你用的是org.json.simple这个库),可以直接参考:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.FileReader;
import java.io.IOException;

public class ExerciseJsonExtractor {
    public static void main(String[] args) {
        JSONParser jsonParser = new JSONParser();
        
        try (FileReader reader = new FileReader("你的JSON文件路径.json")) {
            // 1. 解析顶层JSON数组
            JSONArray topLevelArray = (JSONArray) jsonParser.parse(reader);
            
            // 2. 取出数组里的第一个对象(你的示例里只有这一个)
            JSONObject exerciseWrapper = (JSONObject) topLevelArray.get(0);
            
            // 3. 通过键名获取对应的子数组
            JSONArray exerciseDetailsArray = (JSONArray) exerciseWrapper.get("BUTT LIFT (BRIDGE)");
            
            // 4. 取出子数组里的第一个详情对象
            JSONObject exerciseDetails = (JSONObject) exerciseDetailsArray.get(0);
            
            // 5. 提取你需要的目标值
            String mainMuscle = (String) exerciseDetails.get("Main Muscle Worked");
            String forceType = (String) exerciseDetails.get("Force");
            String difficultyLevel = (String) exerciseDetails.get("Level");
            
            // 测试输出
            System.out.println("主要锻炼肌肉: " + mainMuscle);
            System.out.println("发力类型: " + forceType);
            System.out.println("难度等级: " + difficultyLevel);
            
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }
}

重要注意事项

  • 依赖引入:如果用Maven,记得在pom.xml里加simple-json的依赖:
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>
  • 类型转换:simple-json的解析方法返回的是Object类型,所以必须强制转换成JSONArray或JSONObject,不然会报错。
  • 多元素处理:如果你的JSON数组里有多个锻炼动作对象,记得用循环遍历topLevelArray和exerciseDetailsArray,而不是直接get(0)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:23:50