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

如何在Spring HttpExchange接口中正确使用对象作为请求参数?

解决方案

错误原因

直接使用@RequestParam修饰自定义对象时,Spring会尝试将整个对象转换为String作为单个查询参数的值,但不存在对应的类型转换器,因此抛出ConverterNotFoundException。

正确实现方式

1. 使用@ParameterObject注解替换@RequestParam

Spring 6+提供了@ParameterObject注解,专门用于将自定义对象的字段展开为独立的请求查询参数。修改后的接口代码如下:

@HttpExchange(accept = "application/json", contentType = "application/json")
public interface MyHttpExchange {

    @GetExchange("/api/v1.0/question")
    Mono<String> question(@ParameterObject MyQueryParameters myQueryParameters);

}

2. 自定义字段与查询参数的映射(可选)

如果自定义对象的字段名与第三方API的查询参数名不一致,可以在record的字段上添加@RequestParam指定映射名称:

public record MyQueryParameters(
    @RequestParam("user_id") int id, // 映射到查询参数user_id
    int name,
    int age
) {}

3. 效果验证

调用接口方法时,传入MyQueryParameters对象(如new MyQueryParameters(1,11,111)),Spring会自动生成符合要求的请求:
https://third-party.com/api/v1.0/question?id=1&name=11&age=111

关键说明

@ParameterObject是Spring Web模块提供的注解,用于将对象的属性绑定到请求的查询参数或表单参数上,是处理对象作为请求参数的标准方式,避免了手动转换或使用Map的繁琐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 03:06:02