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

原生Android Java环境JSON解析categories字段类型及取值问题求助

问题根因与类型判定

你之前对JSONArray的格式记忆有误,标准JSON语法中,JSONArray就是直接用[]包裹的有序集合,不需要在外面套一层{}。你提供的示例里categories字段是由字符串类型元素组成的JSONArray,不是JSONObject,因此你之前调用getJSONObject取值的写法会抛出类型不匹配异常。

修正后的代码实现

你可以直接将categories作为JSONArray取出后,根据需求选择转换为字符串的方式:

groups = response.getJSONArray("results");
if (groups.length() > 0) {
    JSONObject resultObject = groups.getJSONObject(0);
    if (resultObject.has("poi")) {
        // 先提取poi对象避免重复取值,效率更高也更易读
        JSONObject poiObject = resultObject.getJSONObject("poi");
        if (poiObject.has("name")) {
            nameResult = poiObject.getString("name");
        } else {
            nameResult = "Information is not available.";
        }
        String categoriesResult = "Information is not available.";
        if (poiObject.has("categories")) {
            // 按JSONArray类型读取categories字段
            JSONArray categoriesArray = poiObject.getJSONArray("categories");
            // 方式1:直接转成标准JSON数组字符串,输出结果为["pub food","restaurant"]
            categoriesResult = categoriesArray.toString();
            
            // 若需要拼接为逗号分隔的普通字符串,注释掉上面一行,启用下方代码即可,输出结果为 pub food,restaurant
            /*
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < categoriesArray.length(); i++) {
                if (i > 0) sb.append(",");
                sb.append(categoriesArray.getString(i));
            }
            categoriesResult = sb.toString();
            */
        }
    }
}

额外注意点

如果你的业务场景中JSON结构可能出现字段类型不匹配的情况,可以新增try-catch捕获JSONException,避免程序直接崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:27:03