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

解析Google Books JSON的industryIdentifiers字段时类型转换错误求助

解决org.json中JSONArray转JSONObject的ISBN提取错误

老哥,我帮你瞅了下代码,核心问题就出在你明明已经正确把industryIdentifiers拿到手作为JSONArray了,结果后续又错误地把它当成JSONObject来读取,这直接触发了类型转换异常,导致应用卡壳。

先帮你理清楚问题根源:你贴的原始JSON里,industryIdentifiers本身就是一个JSON数组(带方括号[]),里面的每个元素才是包含type和identifier的JSONObject。但你的代码里,在拿到JSONArray industryIdentifiers = volumeInfo.getJSONArray("industryIdentifiers");之后,又写了volumeInfo.getJSONObject("industryIdentifiers")——这就相当于告诉程序“把数组当成对象读”,不报错才怪!

修正后的代码(纯org.json库,无额外依赖)

String ISBN = "null";
// 用JSON对象的has()方法判断字段存在,比字符串contains()更可靠
if (volumeInfo.has("industryIdentifiers")) { 
    JSONArray industryIdentifiers = volumeInfo.getJSONArray("industryIdentifiers");
    StringBuilder isbnBuilder = new StringBuilder();
    
    // 遍历数组里的每个ISBN对象
    for (int i = 0; i < industryIdentifiers.length(); i++) {
        JSONObject identifierObj = industryIdentifiers.getJSONObject(i);
        // 用optString可以做容错,避免字段缺失时抛异常
        String isbnType = identifierObj.optString("type", "UNKNOWN_TYPE");
        String isbnValue = identifierObj.optString("identifier", "UNKNOWN_ID");
        
        if (isbnBuilder.length() > 0) {
            isbnBuilder.append(" - ");
        }
        isbnBuilder.append(isbnType).append(": ").append(isbnValue);
    }
    
    ISBN = isbnBuilder.length() > 0 ? isbnBuilder.toString() : "null";
} else {
    ISBN = "null";
}

关键修正点说明

  • 替换字符串判断为JSON原生方法:用volumeInfo.has("industryIdentifiers")替代toString().contains(),避免JSON文本中出现同名字符串但不是字段的误判,逻辑更严谨。
  • 正确遍历JSON数组:直接循环处理industryIdentifiers数组中的每个JSONObject,不再做错误的类型转换。
  • 容错处理:用optString()替代getString(),如果某个ISBN对象缺失type或identifier字段,不会直接抛异常,而是返回你指定的默认值。
  • 性能优化:用StringBuilder拼接结果,避免多次字符串拼接带来的性能损耗,代码也更整洁。

额外提示

如果你的场景中可能出现industryIdentifiers为空数组的情况,代码里的逻辑也能自动处理,最终返回"null",符合你原本的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:22:04