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

使用JSON Simple调用IMGW气象API获取指定站点数据遇阻求助

问题分析与修复方案

先梳理下你代码里的几个关键问题:

  • 目标ID错误:你要找的是id为11的站点,但代码里判断的是id == 12650,这会直接导致找不到目标数据
  • JSON解析方式错误:API返回的是完整的JSON数组,你逐行读取并解析单一行的话,单一行不是有效的JSON结构,会触发ParseException
  • 字段类型强转错误:temperatura字段返回的是数值类型(比如Double),直接强转成String会抛出类型转换异常
  • 提前返回丢失数据:找到目标后直接return stacja,导致temperatura的值没被获取到,无法后续展示

修复后的完整代码

我调整了逻辑,解决了上述问题,同时保证能正确获取目标站点的stacja和temperatura:

// 建议把这两个变量设为类成员,方便后续在TextView中直接调用
private String stacja;
private String temperatura;

public String getTargetStationData() { 
    JSONParser parser = new JSONParser(); 
    try { 
        URL apiUrl = new URL("https://danepubliczne.imgw.pl/api/data/synop"); 
        URLConnection connection = apiUrl.openConnection(); 
        
        // 先读取完整的响应内容,再解析JSON
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder responseContent = new StringBuilder();
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            responseContent.append(inputLine);
        }
        in.close();
        
        // 解析完整的JSON数组
        JSONArray stationList = (JSONArray) parser.parse(responseContent.toString()); 
        for (Object obj : stationList) { 
            JSONObject station = (JSONObject) obj; 
            // API返回的id_stacji是长整型,注意用Long接收
            Long stationId = (Long) station.get("id_stacji"); 
            if (stationId == 11L) { // 改为目标ID 11
                stacja = (String) station.get("stacja"); 
                // 先转成数值类型再转字符串,避免类型错误
                Double tempValue = (Double) station.get("temperatura");
                temperatura = String.valueOf(tempValue);
                // 返回组合信息,或者后续直接用类成员变量
                return stacja + " - 当前温度: " + temperatura;
            } 
        } 
    } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
    } catch (IOException e) { 
        e.printStackTrace(); 
    } catch (ParseException e) { 
        e.printStackTrace(); 
    } 
    return "未找到目标站点数据"; 
}

关键修复点说明

  • 读取完整响应:用StringBuilder拼接所有响应行,得到完整的JSON字符串后再解析,避免逐行解析的格式错误
  • 修正目标ID:把判断条件改成stationId == 11L(Long类型字面量要加L)
  • 处理字段类型:temperatura是数值类型,先转成Double再转成String,避免类型转换异常
  • 保留数据完整性:获取到两个字段后,要么返回组合字符串,要么用类成员变量存储,后续直接在TextView中设置文本(比如textView.setText(stacja + "\n温度: " + temperatura);)

另外要注意:在Android中网络请求不能在主线程执行,你需要把这段代码放在Coroutine、AsyncTask或者异步回调中,否则会触发NetworkOnMainThreadException。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:27:50