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

如何在Rest Assured测试中替换JSON文件值并用于POST请求

解决JSON修改问题及Rest Assured中预定义JSON体的简便处理方式

先搞定你当前的JSON修改错误

你的JSON结构里,items是数组(用[]包裹),不是单个JSON对象,所以之前的两种写法都踩了坑:

  1. 第一种代码直接在外层JSONObject上操作item_ref,等于新增了一个外层键值对,完全没碰数组里的内容,自然得不到想要的结果。
  2. 第二种代码尝试用getJSONObject("items"),但items是数组类型,所以会抛出"JSONObject[\"items\"] is not a JSONObject"的错误。

正确的做法是先定位到items数组,再取出数组里的第一个对象(你的数组只有一个元素),然后修改这个对象的item_ref值。用org.json库的话,代码应该是这样:

JSONObject jObject = new JSONObject(jsonbody);
// 获取items数组,取出索引为0的第一个元素
JSONObject targetItem = jObject.getJSONArray("items").getJSONObject(0);
// 修改item_ref,建议保持和原JSON一致的数字类型,需要字符串的话用"251"即可
targetItem.put("item_ref", 251);
System.out.println(jObject);

运行这段代码后,就能得到你期望的结果:{"items":[{"item_ref":251,"price":100}]}


Rest Assured中处理预定义JSON体的高效方式

针对Rest Assured的POST请求,处理预定义JSON文件有几种更省心的方案,你可以按场景选择:

1. 用Rest Assured自带的JsonPath直接修改

Rest Assured的JsonPath支持精准定位JSON节点并修改,适合简单的字段替换:

// 读取本地JSON文件内容(这里用Apache Commons IO的FileUtils,也可以用Java原生文件读取)
String originalJson = FileUtils.readFileToString(new File("path/to/your/request.json"), StandardCharsets.UTF_8);

// 用JsonPath解析并修改指定节点
JsonPath jsonPath = new JsonPath(originalJson);
jsonPath.set("items[0].item_ref", 251); // 定位数组第一个元素的item_ref

// 发送POST请求
given()
    .contentType(ContentType.JSON)
    .body(jsonPath.prettyPrint())
.when()
    .post("/your-api-endpoint")
.then()
    .statusCode(200);

2. 映射为POJO对象(最推荐的结构化方案)

如果你的JSON结构复杂,或者需要频繁修改多个字段,把JSON映射成Java POJO类是最清晰的方式:
先定义对应的POJO类:

public class Item {
    private int item_ref;
    private int price;

    // 生成getter和setter方法
    public int getItem_ref() { return item_ref; }
    public void setItem_ref(int item_ref) { this.item_ref = item_ref; }
    public int getPrice() { return price; }
    public void setPrice(int price) { this.price = price; }
}

public class RequestBody {
    private List<Item> items;

    // 生成getter和setter方法
    public List<Item> getItems() { return items; }
    public void setItems(List<Item> items) { this.items = items; }
}

然后在测试代码中读取JSON、修改对象、发送请求:

// 用Jackson的ObjectMapper读取JSON文件并反序列化为POJO
RequestBody requestBody = new ObjectMapper()
    .readValue(new File("path/to/your/request.json"), RequestBody.class);

// 修改指定字段
requestBody.getItems().get(0).setItem_ref(251);

// 发送请求,Rest Assured会自动把POJO序列化为JSON
given()
    .contentType(ContentType.JSON)
    .body(requestBody)
.when()
    .post("/your-api-endpoint")
.then()
    .statusCode(200);

3. 使用模板引擎(适合多场景复用的动态JSON)

如果你的JSON需要根据不同测试场景替换多个占位符,可以用Freemarker或Mustache这类模板引擎:
先创建模板文件request-template.json:

{ "items": [ { "item_ref": {{itemRef}}, "price": {{price}} } ] }

然后在代码中加载模板并替换变量:

// 初始化Freemarker配置
Configuration freemarkerCfg = new Configuration(Configuration.VERSION_2_3_31);
freemarkerCfg.setDirectoryForTemplateLoading(new File("path/to/templates"));

// 加载模板
Template template = freemarkerCfg.getTemplate("request-template.json");

// 准备要替换的变量
Map<String, Object> templateData = new HashMap<>();
templateData.put("itemRef", 251);
templateData.put("price", 100);

// 生成最终的JSON字符串
StringWriter writer = new StringWriter();
template.process(templateData, writer);
String finalJson = writer.toString();

// 发送请求
given()
    .contentType(ContentType.JSON)
    .body(finalJson)
.when()
    .post("/your-api-endpoint")
.then()
    .statusCode(200);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:59:47