【发布时间】:2020-12-17 16:06:49
【问题描述】:
我想将 get 参数绑定到我的 DTO。我的问题是映射我的 DTO 拥有的嵌套列表。
控制器类:
@PostMapping(value = "test-endpoint")
public ResponseEntity<String> doStuff(@Valid @RequestParams MyDto myDto) {
// do stuff
}
父级 DTO:
public class MyDto {
@NotNull
private String fieldA;
@Valid
@NotNull
private List<MyNestedDto> nestedDto;
}
嵌套 DTO:
public class MyNestedDto {
@NotNull
private String nestedFieldA;
@NotNull
private String nestedFieldB;
// more fields
}
我有一个向我的控制器发送 POST 请求的服务。请求无法更改,因此我无法使用 @RequestBody 注释。
请求如下所示:
http://localhost:8080/api/test-endpoint?nestedDto={"more":[{"nestedFieldA":"example","nestedFieldB":"example"}]}&fieldA=123
有没有办法绑定嵌套列表来获取参数?
编辑*
注册转换器好像不起作用,我的转换器转换方法甚至没有被调用。
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new MyConverter());
}
}
public class MyConverter implements Converter<String, MyDto> {
@Override
public MyDto convert(String source) {
// it never reaches there
ObjectMapper objectMapper = new ObjectMapper();
return null; // return null for testing purposes
}
}
【问题讨论】:
-
抱歉有什么问题?你想将该 JSON 映射到
@RequestParam -
是的,有没有办法在不更改请求的情况下将该 JSON 映射到 @RequestParam?
-
使用
PostMapping或使用GetMappings? -
你可以在我的控制器上看到它是 PostMapping
-
为什么你使用
POST方法和GET的语义做所有事情?POST您的对象并从@RequestBody获取它或使用GET并独立接收每个参数或使用 Map。建议:使用POST/@RequestBody。