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

如何基于给定站点名称从JSON payload中获取对应温度值

修复方案

错误原因

  • 根节点读取错误:你提供的JSON payload根节点为list,不存在response根字段,jsonObject.get("response")会直接返回null,后续所有解析逻辑都基于空值运行,自然得到null结果。
  • JSON路径层级错误:station_name实际嵌套在station.identity节点下,你代码中直接写station.station_name无法匹配到正确字段。
  • 温度提取语法错误:你写的list.station.station_name=["station1"].obs.temp.temprature是赋值逻辑,不是筛选逻辑,完全不符合JSON取值规则。
  • 解析逻辑冗余:你已经用JsonPath完成了解析,不需要再调用JsonSlurper重复解析。

最优修复代码(无需循环,一步筛选)

import com.jayway.jsonpath.JsonPath
import java.io.FileReader

try (def reader = new FileReader("src/test/resources/jsonPayload/response.json")) {
    // 直接按条件筛选出station1对应的温度值
    def Temperature = JsonPath.read(reader, '$.list[?(@.station.identity.station_name == "station1")].obs.temp.temprature')[0]
    // 输出验证结果为13.2
}

兼容原有循环逻辑的修复代码

import com.jayway.jsonpath.JsonPath
import org.json.simple.parser.JSONParser
import java.io.FileReader

JSONParser parser = new JSONParser()

try (def reader = new FileReader("src/test/resources/jsonPayload/response.json")) {
    def jsonContent = parser.parse(reader).toString()
    def js = new JsonPath(jsonContent)
    int size = js.getInt("list.size()")
    def Temperature = null
    
    for (int i = 0; i < size; i++) {
        def currentStation = js.getString("list[$i].station.identity.station_name")
        if ("station1" == currentStation) {
            Temperature = js.getDouble("list[$i].obs.temp.temprature")
            break
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:39:01