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

Android中如何遍历Volley请求返回的服务器JSONObject?

问题:如何遍历Volley返回的指定JSONObject结构?

我现在正在做一个功能:从服务器获取带描述及其他信息的图片,使用Volley框架实现,图片按类别划分。用户点击按钮时,向服务器POST表名,服务器返回对应图片数据,当前采用POST JSONObject请求方式。

现有Java请求代码

public void getJsonResponsePost(View v){ 
    JSONObject json = new JSONObject(); 
    try { 
        json.put("table","aad"); 
    } catch (JSONException e) { 
        e.printStackTrace(); 
    } 
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json, 
        new Response.Listener<JSONObject>() { 
            @Override 
            public void onResponse(JSONObject response) { 
                Log.d(TAG, response.toString()); 
            } 
        }, 
        new Response.ErrorListener() { 
            @Override 
            public void onErrorResponse(VolleyError error) { 
                Log.d(TAG, "Error: " + error.getMessage()); 
                serverResp.setText("String Response : " + error.getMessage()); 
            } 
        }); 
    jsonObjectRequest.setTag(REQ_TAG); 
    MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest); 
}

PHP后端代码

header('Content-Type: application/json'); 
include '../../script/database.php'; 
$response =array(); 
$data = json_decode(file_get_contents('php://input'), true); 
$table = $data["table"]; 
$sql = "select * from $table WHERE (dp='1') LIMIT 1"; 
$query = mysqli_query($db, $sql); 
$post_data_array = array(); 
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { 
    $img = $row['image']; 
    $id_image = $row['id']; 
    $weight = $row['weight']; 
    $row_date = $row['date']; 
    $image_path = $row['path']; 
    $image = "http://192.168.43.138/djp/" . $image_path . $row['image']; 
    $post_data_array[] = array( 
        'image' => $image, 
        'weight' => $weight, 
        'date' => $date 
    ); 
} 
$post_data = json_encode(array('item' => $post_data_array), JSON_FORCE_OBJECT); 
echo $post_data;
?>

返回的JSONObject结构

{"item":{"0":{"image":"http:\/\/192.168.43.238\/djp\/aad\/aad002.jpg","weight":"15","date":""}}}

我的问题

现在该如何遍历这个JSONObject的内容?


解答

嘿,我来帮你搞定这个遍历的问题!从你给出的JSON结构来看,外层是一个包含item键的对象,而item对应的又是一个以数字为键的对象(这是因为PHP后端用了JSON_FORCE_OBJECT把数组强制转成了对象结构)。

你可以按照以下步骤来遍历这个结构:

  1. 先提取外层的item对象:在Volley的onResponse回调里,从返回的response中取出item对应的JSONObject。
  2. 遍历item对象的所有键:用keys()方法拿到item对象所有键的迭代器,逐个遍历这些数字键。
  3. 获取每个子对象的具体字段:对每个键,取出对应的子JSONObject,然后提取image、weight、date这些你需要的数据。

修改后的onResponse代码示例

直接把这段代码替换你原来的回调逻辑就行:

@Override
public void onResponse(JSONObject response) {
    Log.d(TAG, response.toString());
    try {
        // 第一步:获取外层的item对象
        JSONObject itemObj = response.getJSONObject("item");
        
        // 第二步:获取item对象所有键的迭代器
        Iterator<String> keys = itemObj.keys();
        
        // 第三步:遍历每个键,取出对应的图片数据
        while (keys.hasNext()) {
            String key = keys.next();
            JSONObject imageData = itemObj.getJSONObject(key);
            
            // 提取你需要的字段
            String imageUrl = imageData.getString("image");
            String weight = imageData.getString("weight");
            String date = imageData.getString("date");
            
            // 这里就可以用这些数据做后续操作了,比如用Glide加载图片、显示重量和日期
            Log.d(TAG, "图片地址:" + imageUrl);
            Log.d(TAG, "重量:" + weight);
            Log.d(TAG, "日期:" + date);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        Log.e(TAG, "JSON解析出错:" + e.getMessage());
    }
}

额外优化建议

你的PHP后端用了JSON_FORCE_OBJECT,导致返回的item是对象而不是数组。如果后端去掉这个参数,返回的JSON会变成数组结构:

{"item":[{"image":"http:\/\/192.168.43.238\/djp\/aad\/aad002.jpg","weight":"15","date":""}]}

这样遍历起来会更直观,用JSONArray处理即可,代码也更简洁:

修改后的PHP代码(去掉JSON_FORCE_OBJECT)

$post_data = json_encode(array('item' => $post_data_array));

对应Java遍历代码

@Override
public void onResponse(JSONObject response) {
    Log.d(TAG, response.toString());
    try {
        // 获取item对应的JSON数组
        JSONArray itemArray = response.getJSONArray("item");
        
        // 遍历数组中的每个元素
        for (int i = 0; i < itemArray.length(); i++) {
            JSONObject imageData = itemArray.getJSONObject(i);
            String imageUrl = imageData.getString("image");
            String weight = imageData.getString("weight");
            String date = imageData.getString("date");
            
            // 处理数据
            Log.d(TAG, "第" + (i+1) + "张图片:" + imageUrl);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

两种方式都能解决问题,看你更习惯哪种结构啦!


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:22:35