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

如何使用Rest Assured在POST请求体中传入POJO数组?

解决Rest Assured POST请求中POJO数组请求体的问题

很简单的,你只需要把你的Collections对象包装进一个数组或者List集合里,Rest Assured会自动帮你序列化成符合要求的JSON数组格式。下面给你两种常用的实现方式:

方式一:使用List集合包装

先实例化并配置你的Collections对象,然后把它放到ArrayList(或者其他List实现类)中,直接传给请求的body()方法即可:

// 1. 创建并配置Collections对象
Collections collection = new Collections();
collection.setReference("test");
collection.setCollectionDate("test");

// 2. 把对象放入List
List<Collections> collectionList = new ArrayList<>();
collectionList.add(collection);

// 3. 发送POST请求
given()
    .contentType(ContentType.JSON)
    .body(collectionList)
.when()
    .post("你的API接口URL")
.then()
    .statusCode(200); // 根据实际预期状态码调整

方式二:直接使用数组包装

如果不想用List,也可以直接用Java数组来包装,写法更简洁:

// 1. 创建并配置Collections对象
Collections collection = new Collections();
collection.setReference("test");
collection.setCollectionDate("test");

// 2. 直接用数组包装
Collections[] collectionArray = {collection};

// 3. 发送POST请求
given()
    .contentType(ContentType.JSON)
    .body(collectionArray)
.when()
    .post("你的API接口URL")
.then()
    .statusCode(200);

为什么这样可行?

Rest Assured默认会使用Jackson(或Gson,取决于你的依赖)来序列化Java对象到JSON。当你传入一个数组或List时,序列化后的结果就是API要求的[{reference:"test",collectionDate:"test"}]格式,完全符合需求。

另外,你的Collections类已经有了正确的getter和setter方法,这是序列化成功的前提,所以不需要额外修改POJO类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 13:32:35