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

Java解析Get请求响应获取referentiel字段遇JSONException求助

问题分析与修正方案

你碰到的org.json.JSONException核心原因很明确:你把单个JSON对象当成JSON数组来解析了!

看你的响应示例,返回的是一个单独的JSON对象结构:

{ 
  "status": "livre", 
  "referentiel": "000001498675", 
  "digitalid": "00004328", 
  "nom": "SAMI IDRISS", 
  "date": "10/04/2018 00:00:00", 
  "email": "", 
  "mobile": "123456789", 
  "Compte_principale": "0821006348788", 
  "Login": "Sami" 
}

而你的代码里却用JSONArray JA = new JSONArray(data);去解析,这就会触发JSONException——因为输入的JSON不是数组格式。

修正后的完整代码

try {
    URL url = new URL(url1);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    // 用try-with-resources自动关闭流,避免资源泄漏
    try (InputStream inputStream = httpURLConnection.getInputStream();
         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
        
        String line;
        StringBuilder data = new StringBuilder(); // 用StringBuilder更高效,避免字符串拼接的性能问题
        while ((line = bufferedReader.readLine()) != null) {
            data.append(line);
        }
        
        // 直接解析为单个JSONObject,而不是JSONArray
        JSONObject JO = new JSONObject(data.toString());
        String singleParsed = JO.getString("referentiel"); // 用getString更安全,避免类型转换问题
        String dataParsed = singleParsed + "\n"; // 这里可以根据你的需求调整拼接逻辑
        
        // 输出或使用解析后的referentiel值
        System.out.println("referentiel: " + singleParsed);
    }
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (JSONException e) {
    e.printStackTrace();
}

关键修正点

  • 替换JSONArray为JSONObject:匹配响应的实际格式
  • 使用StringBuilder拼接响应内容:比直接data = data + line更高效,尤其是响应内容较长时
  • 用JO.getString("referentiel")替代JO.get("referentiel"):明确获取字符串类型,避免不必要的类型转换
  • 加入try-with-resources:自动关闭输入流和BufferedReader,防止资源泄漏

这样修改后,就能正确提取referentiel字段的值,不会再触发JSONException了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:19:25