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

API测试:如何用Rest Assured结合JSONObject发送POST数组对象

在Rest Assured中使用JSONObject发送包含数组对象的POST请求

没问题!要发送你需要的这种包含数组对象的请求体,只需要在主JSONObject里嵌套JSONArray就可以实现,我来给你一步步拆解:

你之前处理普通字符串请求体的写法是这样的:

JSONObject json = new JSONObject();
json.put("firstname", "John");
json.put("lastname", "James");
request.body(json.toJSONString());
request.post("/my/post/url/end/point");

要构建你需要的带owner数组的请求体,只需要额外创建一个JSONArray来存放数组里的对象,再把这个数组放到主JSONObject中就行,完整代码如下:

// 1. 创建主请求体的JSONObject
JSONObject json = new JSONObject();
json.put("price", "234");
json.put("phoneNumber", "09022334422");

// 2. 创建存放owner对象的JSONArray
JSONArray ownerArray = new JSONArray();

// 3. 创建数组里的单个owner对象
JSONObject ownerObj = new JSONObject();
ownerObj.put("digits", "1122334455");
ownerObj.put("myname", "Abisoye Haminat");
ownerObj.put("code", "058");
ownerObj.put("default", "true");

// 4. 将owner对象添加到数组中
ownerArray.put(ownerObj);

// 5. 将数组放入主JSONObject
json.put("owner", ownerArray);

// 6. 发送POST请求
request.body(json.toJSONString());
request.post("/my/post/url/end/point");

如果你的owner数组需要包含多个对象,只需要重复步骤3和4,创建更多的ownerObj并添加到ownerArray里就可以了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:00:31