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

如何在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 a JSONArray, you ensure the API receives a properly formatted array like ["11","3"] instead of a string.
  • Error Handling: Wrapping JSON operations in a try-catch block 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:01:56