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

Java调用API时请求体传递整数数组的格式异常问题

解决Java中构造API请求体数组格式不符的问题

嘿,我一眼就发现问题所在了!你当前代码里的Arrays.toString(arr)是罪魁祸首——这个方法会把整数数组转换成带方括号和空格的普通字符串(比如"[1, 2]"),而不是JSON规范的数组类型。当你把这个字符串塞进JSONObject后,最终生成的请求体里id对应的是字符串值,而非数组,自然就和预期的{"id": [1,2]}格式不符了。

下面给你几种可行的解决办法:

方法1:直接将数组传入JSONObject(推荐)

如果你使用的是org.json这类支持直接序列化数组的JSON库,只需要去掉Arrays.toString(),直接把数组传入put方法即可,库会自动帮你转换成JSON数组:

JSONObject jsonObject = new JSONObject();
jsonObject.put("id", arr); // 直接传入int数组,无需转字符串
String stringBody = jsonObject.toJSONString();

RequestSpecification specification = RestAssured.with();
specification.body(stringBody);
Response response = specification.post(endpoint);

方法2:手动构造JSONArray

如果你的JSON库不支持直接传入数组,那就手动把整数数组转成JSONArray再放入JSONObject:

JSONObject jsonObject = new JSONObject();
JSONArray idArray = new JSONArray();
for (int num : arr) {
    idArray.put(num);
}
jsonObject.put("id", idArray);
String stringBody = jsonObject.toJSONString();

RequestSpecification specification = RestAssured.with();
specification.body(stringBody);
Response response = specification.post(endpoint);

方法3:利用RestAssured的自动序列化(更简洁)

RestAssured本身支持直接将Java对象(比如Map)序列化为JSON,完全不用手动拼接JSON字符串,代码会更简洁且不易出错:

Map<String, Object> requestBody = new HashMap<>();
requestBody.put("id", arr); // 直接放入数组

RequestSpecification specification = RestAssured.with();
specification.body(requestBody); // RestAssured自动转成正确的JSON格式
Response response = specification.post(endpoint);

你可以根据自己使用的JSON库和代码习惯选择其中一种方法,测试后就能得到符合预期的{"id": [1,2]}请求体啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:20:23