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

Android嵌套JSON对象取值报错:org.json.JSONException无code值

解决JSON解析的嵌套属性获取问题

嘿,我一眼就看到你代码里的几个问题啦,这就帮你一步步修复:

问题根源

  1. 返回的JSON是单个对象而非数组:你提供的返回数据是{"id":25,...}这种单个JSONObject结构,但你却用JSONArray去解析,这会导致后续的循环逻辑完全不适用,还可能隐藏其他问题。
  2. 嵌套属性获取方式错误:code是嵌套在country对象里的,type的id也是嵌套对象的属性,你直接从顶层JSONObject调用get("code"),自然会抛出No value for code的异常。

修正后的代码

try{
    // 注意:返回的是单个JSONObject,不是JSONArray
    JSONObject jsonObject = new JSONObject(sb.toString());
    Courses coun = new Courses();
    
    // 顶层属性直接获取
    coun.setName(jsonObject.getString("name"));
    coun.setId(jsonObject.getInt("id"));
    coun.setDescription(jsonObject.getString("description"));
    coun.setDishesNumber(jsonObject.getInt("dishes_number"));
    
    // 获取嵌套的country对象,再取code属性
    JSONObject countryObj = jsonObject.getJSONObject("country");
    coun.setCountryCode(countryObj.getString("code"));
    
    // 获取嵌套的type对象,再取id属性
    JSONObject typeObj = jsonObject.getJSONObject("type");
    coun.setCourseTypeId(typeObj.getInt("id"));
    
    repas.add(coun);
}catch (JSONException je){
    je.printStackTrace();
};

额外提示

  • 尽量使用getString()、getInt()这类类型明确的方法,比直接强制转换更安全,能避免类型不匹配的异常。
  • 如果接口可能返回数组格式,一定要先确认接口文档的返回结构,避免解析类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:36:23