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

Spring Boot中如何向RequestBody传递多个动态参数

实现RequestBody传递多个动态String值的方案

你当前的代码是将单个对象序列化为JSON作为请求体,要传递多个动态String值,核心是构造一个包含这些String的JSON结构(因为Content-Type是application/json),以下是两种实用方案:

方案一:用Map灵活封装动态键值对

这种方式适合需要动态增减字段的场景,无需额外创建类:

private JsonObject gateWayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, ObjectWriter ow) throws IOException {
    String brandwiseBearerToken = "";
    String brandwiseURL = "";
    OkHttpClient client = new OkHttpClient();
    MediaType mediaType = MediaType.parse("application/json");

    // 1. 创建Map存放多个动态String键值对
    Map<String, String> dynamicData = new HashMap<>();
    dynamicData.put("username", "动态用户名"); // 替换为你的实际动态值
    dynamicData.put("orderId", "动态订单ID");
    // 可根据需求添加更多字段

    // 2. 将Map序列化为JSON字符串
    String requestJson = ow.writeValueAsString(dynamicData);
    // 如果你用Gson,也可以写成:String requestJson = new Gson().toJson(dynamicData);

    // 3. 构造RequestBody
    RequestBody body = RequestBody.create(mediaType, requestJson);
    
    Request request = new Request.Builder().url(brandwiseURL).post(body)
            .addHeader("Content-Type", "application/json").addHeader("Bearer", brandwiseBearerToken)
            .build();
    Response response = client.newCall(request).execute();
    ResponseBody responseBody = response.body();
    return new Gson().fromJson(responseBody.string(), JsonObject.class);
}

方案二:扩展/创建DTO类(适合固定字段场景)

如果你的多个String字段是固定的,也可以创建一个专门的DTO类来封装,和你现有的ThirdPartyPaymentGatewayToken用法一致:

// 自定义DTO类,包含需要的多个String字段
public class MultiStringRequest {
    private String field1;
    private String field2;
    // 按需添加更多字段,以及对应的getter/setter

    // 构造方法
    public MultiStringRequest(String field1, String field2) {
        this.field1 = field1;
        this.field2 = field2;
    }
}

然后在方法中使用这个类:

// 传入动态值实例化DTO
MultiStringRequest requestDto = new MultiStringRequest("动态值1", "动态值2");
String requestJson = ow.writeValueAsString(requestDto);
RequestBody body = RequestBody.create(mediaType, requestJson);

补充:保留原有对象同时添加动态字段

如果需要同时传递原有ThirdPartyPaymentGatewayToken的字段和新的动态String,可以把对象转成Map后合并:

// 将原有对象转成Map(Jackson的ObjectWriter支持此方法)
Map<String, Object> combinedData = ow.writeValueAsMap(thirdPartyPaymentGatewayToken);
// 添加新的动态String字段
combinedData.put("newDynamicField", "新动态值");
// 转成JSON字符串
String requestJson = ow.writeValueAsString(combinedData);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:37:00