java - @RequestParam 对象中的枚举列表

标签 java spring-boot rest spring-mvc enums

假设我在 Spring Boot Controller 中有一个 GET 端点,它接受一个对象作为 @RequestParam

@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam FilterParams filterParams) {
  return fooDao.getFoos(filterParams);
}

其中 FilterParams 是一个包含 List 属性(或任何其他对象列表)的类

public class FilterParams {
  public List<Bar> bars;
}

Bar 是一个枚举(对于本例)

public enum Bar {
  Baz, Zap
}

如果我们在此端点上发布 GET 请求,其中包含由“,”分隔的 filterParameter 属性列表,即 curl -X GET localhost:8080/foos?bars=BAZ,ZAP,Spring 无法将其解析为 List,并尝试将一个单一值 BAZ,ZAP 反序列化为一个枚举。如果它不是枚举,它的行为也会相同,即将参数 id=1,2 反序列化为字符串列表的单个元素。是否可以覆盖此行为?如果是这样,如何实现这一目标?

我确实知道我可以通过将多个参数声明为 /foos?bars=BAZ&bars=ZAP 来实现此目的,但这对我来说并不方便

最佳答案

我认为查询参数不会转换为对象。处理这种情况的另一种方法是将请求参数声明为字符串。更新您的文档以说明请求参数支持逗号分隔值。您可以解析此字符串并将其映射到枚举。从长远来看,当您想要支持新值(value)观时,这种方法将会有所帮助。

@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam("bars") String filterParams) {
// Parse the String using coma as delimiter, map the String to an enum so that enum can be passed arround in the code
  return fooDao.getFoos(filterParams);
}

现在应该可以传递以下 URL:curl -X GET localhost:8080/foos?bars=BAZ,ZAP

另一种方法是将查询参数声明为列表。

@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam("bar") List<String> filterParams) {
// Parse the String using coma as delimiter, map the String to an enum so that enum can be  passed arround in the code
  return fooDao.getFoos(filterParams);
}

在这种情况下,根据您的服务支持的参数数量,URL 可能会变长:curl -X GET localhost:8080/foos?bar=BAZ&bar=ZAP

关于java - @RequestParam 对象中的枚举列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62022756/

相关文章:

java - Spring Boot - 添加外部属性文件

java - 如何在 Spring Boot 中使用 Java 通过更改 JSON 结构中的字段名称(如本例所示)从 JSON 响应中提取特定部分?

spring - Spring boot遵循 “Opinionated Defaults Configuration”方法是什么意思?

java - 根据同一行中的另一列更新 sql 列

java - 上下文路径与 webapp-runner 中的 Spring UrlTag 冲突?

node.js - *类型错误: Cannot read property 'body' of undefined* when implementing REST API with nodejs to add new data to database

python - 无法使用 Ryu REST Controller 在 mininet 中的两台主机之间建立连接

spring - 使用 Spring Integration 客户端的持久连接/连接重用

c# - AES需要使用Java吗?

java - 如何将对象从ArrayList传输到LinkedList