如何在Volley的JsonObject Post请求中传入String[]数组
Fixing Volley POST Request with JSON Array
Hey there, the issue you’re running into is that directly passing a Java String[] to JSONObject.put() doesn’t serialize it into a proper JSON array—it instead converts the array to a raw string (like "[11,3]"), which won’t match what your API expects.
Here’s the straightforward fix: you need to convert your String[] into a JSONArray first, then add that to your JSONObject.
Corrected Code Example
private void assign() { String url = "YOUR_API_ENDPOINT_URL"; // Replace with your actual API URL JSONObject object = new JSONObject(); try { object.put("id", id); // Convert your String array to a JSONArray String roles[] = {"11", "3"}; JSONArray rolesJsonArray = new JSONArray(); for (String role : roles) { rolesJsonArray.put(role); } object.put("roles", rolesJsonArray); object.put("no_people", people); object.put("notes", "special"); // Set up Volley's JsonObjectRequest to send the data JsonObjectRequest postRequest = new JsonObjectRequest( Request.Method.POST, url, object, response -> { // Handle successful response here Log.d("VolleySuccess", "Response received: " + response.toString()); }, error -> { // Handle request errors here Log.e("VolleyError", "Request failed: " + error.getMessage()); } ); // Add the request to Volley's request queue to execute it Volley.newRequestQueue(this).add(postRequest); } catch (JSONException e) { e.printStackTrace(); Log.e("JSONError", "Failed to build JSON object: " + e.getMessage()); } }
Key Details to Note:
- JSONArray Conversion: By looping through your
String[]and adding each element to aJSONArray, you ensure the API receives a properly formatted array like["11","3"]instead of a string. - Error Handling: Wrapping JSON operations in a
try-catchblock catches any invalid JSON formatting issues (like missing keys or invalid values). - Volley Queue: Don’t forget to add your request to Volley’s queue—this is what actually sends the POST request to your API.
Content of the question originates from Stack Exchange, question author Satyam Gondhale
相关产品推荐
相关产品推荐

