Spring REST Controller如何处理JSON数组格式的请求参数
问题分析与解决方案
问题根源:Spring默认处理@RequestParam修饰的List类型参数时,会将请求参数值按逗号分割成多个元素。但你的请求中params是一个完整的JSON数组字符串(["param1", "param2", "param3"]),其中的逗号属于JSON结构的一部分,因此被错误分割,导致得到包含多余引号和括号的元素。
下面提供两种无需修改请求的解决方案:
方法1:直接接收字符串并手动解析(快速实现)
直接将参数接收为String类型,再用Spring自带的Jackson库将JSON数组字符串解析为List<String>:
@RestController @RequestMapping("/test") public class TestController { private final ObjectMapper objectMapper; // 注入Spring容器中的ObjectMapper实例 public TestController(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @GetMapping("/get") public List<String> test(@RequestParam String params) throws IOException { // 解析JSON数组字符串为List<String> return objectMapper.readValue(params, new TypeReference<List<String>>() {}); } }
方法2:自定义参数解析器(全局复用,更优雅)
如果多个接口需要处理这类参数,可以自定义参数解析器,让Spring自动完成JSON数组到List<String>的转换:
1. 定义自定义注解
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface JsonListParam { // 指定请求参数名,默认使用方法参数名 String value() default ""; }
2. 实现参数解析器
public class JsonListArgumentResolver implements HandlerMethodArgumentResolver { private final ObjectMapper objectMapper; public JsonListArgumentResolver(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public boolean supportsParameter(MethodParameter parameter) { // 仅处理带有@JsonListParam注解的List<String>类型参数 return parameter.hasParameterAnnotation(JsonListParam.class) && List.class.isAssignableFrom(parameter.getParameterType()) && String.class.equals(GenericTypeResolver.resolveTypeArgument(parameter.getParameterType(), List.class)); } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { JsonListParam annotation = parameter.getParameterAnnotation(JsonListParam.class); String paramName = StringUtils.hasText(annotation.value()) ? annotation.value() : parameter.getParameterName(); String paramValue = webRequest.getParameter(paramName); return paramValue == null ? Collections.emptyList() : objectMapper.readValue(paramValue, new TypeReference<List<String>>() {}); } }
3. 注册解析器到Spring MVC
@Configuration public class WebMvcConfig implements WebMvcConfigurer { private final ObjectMapper objectMapper; public WebMvcConfig(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { resolvers.add(new JsonListArgumentResolver(objectMapper)); } }
4. 在Controller中使用
@RestController @RequestMapping("/test") public class TestController { @GetMapping("/get") public List<String> test(@JsonListParam("params") List<String> stringList) { return stringList; } }
内容的提问来源于stack exchange,提问作者qwe ewq
相关产品推荐
相关产品推荐

