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

Android如何正确解析JSONObject取值并设置到TextView

错误原因
  • 核心类型判断错误:接口返回的customer字段是大括号包裹的嵌套JSONObject对象,不是方括号包裹的JSONArray数组。你强行调用getJSONArray("customer")会直接抛出JSONException,代码进入catch分支,完全不会执行TextView赋值逻辑。

区分规则:JSON结构中{}包裹的是对象(JSONObject),[]包裹的是数组(JSONArray),你拿到的customer字段内容是{"name":"Adene Jonah","address":"..."},明显是对象结构。

  • 其他问题:
    • 第二段代码存在语法错误,ar.getString(0).末尾多余的点会直接导致编译失败
    • 第一段代码只是将整个customer对象转为字符串输出,没有提取内部的具体字段值,不符合你取name字段的需求
正确实现代码

按照JSON实际嵌套结构,先从根对象取出customer对应的JSONObject,再从这个嵌套对象里取name等目标字段即可:

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    // 需要控制进度条可以放开注释
    // view_member__progressBar.setVisibility(View.GONE);

    try {
        // 1. 将返回字符串转为根JSON对象
        JSONObject rootObject = new JSONObject(s);
        // 2. 取出customer对应的嵌套JSON对象(注意是getJSONObject不是getJSONArray)
        JSONObject customerObj = rootObject.getJSONObject("customer");
        // 3. 从customer对象中提取需要的字段
        String name = customerObj.getString("name");
        String address = customerObj.getString("address");
        String util = customerObj.getString("util");
        String minimumAmount = customerObj.getString("minimumAmount");
        
        // 4. 给TextView赋值,示例为单独设置name,需要展示多个字段可自行拼接
        detail.setText(name);
        // 多字段拼接示例:detail.setText("姓名:" + name + "\n地址:" + address);

    } catch (JSONException e) {
        e.printStackTrace();
        // 解析失败时设置默认提示,避免页面空白
        detail.setText("数据加载失败");
    }
}
容错优化建议

如果后续接口可能出现字段缺失的情况,可以用optString替代getString,避免字段不存在时直接崩溃,第二个参数为字段缺失时返回的默认值:

String name = customerObj.optString("name", "未获取到姓名");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 03:24:28