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

Java中如何用JayWay JsonPath访问JSON嵌套的Award对象数据?

解决嵌套JSON字符串中的Award数据提取问题

问题根源

你遇到的空结果问题,核心原因是目标JSON里第二个text字段的内容是序列化后的JSON字符串,而非原生的JSON层级结构。JsonPath只会解析原始JSON的节点,无法自动识别并穿透字符串内部的JSON内容,所以直接用$.resultSet.rows..text..AwardID无法提取到数据。


解决方案步骤

1. 精准定位目标JSON字符串

首先用JsonPath精准定位到每个rows元素下values数组的**第二个元素(索引为1)**的text值,避免模糊匹配带来的冗余数据:

// 提取所有rows下values数组第二个元素的text内容
List<String> awardJsonStrings = JsonPath.read(stringJsonResponse, "$.resultSet.rows[*].values[1].text");

2. 解析JSON字符串并提取Award数据

将每个拿到的JSON字符串单独解析为JSON对象,再从中提取allocations数组中的Award数据,最后封装为Java对象。

方式一:用Jackson序列化工具(推荐)

先定义对应Java实体类:

// Award实体类,按需添加字段和getter/setter
public class Award {
    private String AwardID;
    // 其他字段如需要可补充

    public String getAwardID() {
        return AwardID;
    }

    public void setAwardID(String awardID) {
        AwardID = awardID;
    }
}

// 用于包裹allocations数组的中间类
public class AllocationWrapper {
    private List<Award> allocations;

    public List<Award> getAllocations() {
        return allocations;
    }

    public void setAllocations(List<Award> allocations) {
        this.allocations = allocations;
    }
}

然后遍历解析每个JSON字符串:

ObjectMapper objectMapper = new ObjectMapper();
List<Award> allAwards = new ArrayList<>();

for (String jsonStr : awardJsonStrings) {
    // 将字符串解析为AllocationWrapper对象
    AllocationWrapper wrapper = objectMapper.readValue(jsonStr, AllocationWrapper.class);
    if (wrapper.getAllocations() != null) {
        allAwards.addAll(wrapper.getAllocations());
    }
}

// 最终allAwards集合中包含所有提取到的Award对象
logger.info("提取到的Award总数:" + allAwards.size());
方式二:继续使用JsonPath解析字符串

如果不想引入Jackson,也可以用JsonPath直接解析每个JSON字符串:

List<Award> allAwards = new ArrayList<>();
TypeRef<List<Award>> awardListType = new TypeRef<List<Award>>() {};

for (String jsonStr : awardJsonStrings) {
    // 从字符串中提取allocations下的所有Award对象
    List<Award> awards = JsonPath.parse(jsonStr).read("$.allocations[*]", awardListType);
    allAwards.addAll(awards);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:30:52