Android Volley获取带键名JSON数组元素方法求助
Let's get your Volley JSON array retrieval working—here's what's going wrong and how to fix it step by step.
1. Clarify the JSON Response Structure
You mentioned the JSON has key names—this means the response is likely a JSON Object that contains your target array, not a root-level JSON Array. For example, a valid response might look like this (I fixed the comma typo in your example, since valid JSON uses dots for decimal separators):
{ "values": [1579.39734, 2523679.59824966966, 4327116] }
If you're using JsonArrayRequest but the root is a JSON Object, that's a major reason your code is failing. Let's adjust the request type accordingly.
2. Correct Volley Request Implementation
Here are complete, working examples for both possible response structures:
Case A: Response is a root-level JSON Array
If the server returns exactly [1579.39734, 2523679.59824966966, 4327116] (no outer object), use JsonArrayRequest with proper error handling:
private void loadJsonArray() { // Initialize progress dialog (finish your incomplete code here) ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); JsonArrayRequest jsArrayRequest = new JsonArrayRequest( Request.Method.POST, // Switch to GET if the server doesn't require POST new_url, null, // Add a JSONObject here if POST requires parameters new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { pDialog.dismiss(); double[] value = new double[response.length()]; try { // Extract each element from the array for (int i = 0; i < response.length(); i++) { value[i] = response.getDouble(i); } // Use your value array (e.g., update UI or process data) Log.d("Volley", "Loaded values: " + Arrays.toString(value)); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Failed to parse JSON", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { pDialog.dismiss(); // Debug the error to identify the root cause String errorMessage; if (error instanceof NetworkError) { errorMessage = "Network error! Check your internet connection."; } else if (error instanceof ParseError) { errorMessage = "Invalid JSON response from server."; } else if (error instanceof ServerError) { errorMessage = "Server error. Try again later."; } else { errorMessage = error.getMessage() != null ? error.getMessage() : "Unknown error"; } Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show(); Log.e("Volley Error", error.toString()); } }); // Add the request to Volley's request queue Volley.newRequestQueue(this).add(jsArrayRequest); }
Case B: Response is a JSON Object containing the array
If the response has a key (like "values"), use JsonObjectRequest instead to access the nested array:
private void loadJsonArray() { ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); JsonObjectRequest jsObjRequest = new JsonObjectRequest( Request.Method.POST, new_url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { pDialog.dismiss(); try { // Retrieve the array using its key name (replace "values" with your actual key) JSONArray jsonArray = response.getJSONArray("values"); double[] value = new double[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { value[i] = jsonArray.getDouble(i); } // Use your value array Log.d("Volley", "Loaded values: " + Arrays.toString(value)); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Failed to parse JSON", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { pDialog.dismiss(); // Same error handling as above String errorMessage; if (error instanceof NetworkError) { errorMessage = "Network error! Check your internet connection."; } else if (error instanceof ParseError) { errorMessage = "Invalid JSON response from server."; } else if (error instanceof ServerError) { errorMessage = "Server error. Try again later."; } else { errorMessage = error.getMessage() != null ? error.getMessage() : "Unknown error"; } Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show(); Log.e("Volley Error", error.toString()); } }); Volley.newRequestQueue(this).add(jsObjRequest); }
3. Key Fixes for Your Original Code
- Added Error Handling: The missing
ErrorListenerwas probably hiding why your code failed—now you'll get clear feedback on network issues, invalid JSON, or server errors. - Proper JSON Parsing: Wrapped parsing in a
try-catchblock to handle exceptions like invalid indices or wrong data types. - Handled Both Response Structures: Covered both root array and object-containing-array cases since you mentioned "key names" in the response.
- Cleaned Up Progress Dialog: Ensured the dialog is dismissed in both success and error cases to avoid memory leaks.
4. Additional Tips
- Verify the JSON response using tools like Postman or curl to confirm its structure and validity.
- If using POST, make sure you're sending any required parameters (replace
nullwith aJSONObjectof key-value pairs if needed). - Ensure your app has the
INTERNETpermission inAndroidManifest.xml:<uses-permission android:name="android.permission.INTERNET" />
内容的提问来源于stack exchange,提问作者Kah Hao

