[英]Spring Rest - bind nested DTO object to @RequestParams
I want to bind get params to my DTO.我想将 get 参数绑定到我的 DTO。 My problem is mapping the nested list my DTO has.我的问题是映射我的 DTO 拥有的嵌套列表。
controller class: controller class:
@PostMapping(value = "test-endpoint")
public ResponseEntity<String> doStuff(@Valid @RequestParams MyDto myDto) {
// do stuff
}
parent DTO:父 DTO:
public class MyDto {
@NotNull
private String fieldA;
@Valid
@NotNull
private List<MyNestedDto> nestedDto;
}
Nested DTO:嵌套 DTO:
public class MyNestedDto {
@NotNull
private String nestedFieldA;
@NotNull
private String nestedFieldB;
// more fields
}
I have a service that sends a POST request to my controller.我有一个向我的 controller 发送 POST 请求的服务。 The request cannot be changed hence why I can't use @RequestBody
annotation.请求无法更改,因此我不能使用@RequestBody
注释。
The request looks like that:请求如下所示:
http://localhost:8080/api/test-endpoint?nestedDto={"more":[{"nestedFieldA":"example","nestedFieldB":"example"}]}&fieldA=123
Is there a way to bind the nested list to get params?有没有办法绑定嵌套列表来获取参数?
Edit *编辑*
Registering a converter doesn't seem to work, my converter convert method is not even called.注册转换器似乎不起作用,甚至没有调用我的转换器转换方法。
@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
}
}
public class AController {
private final ObjectMapper objectMapper;
private final Validator validator;
public AController(ObjectMapper objectMapper,Validator validator){
this.objectMapper = objectMapper;
this.validator = validator;
}
@PostMapping(value = "test-endpoint")
public ResponseEntity<String> doStuff(@RequestParam("nestedDto") String nestedDto) {
MyDto myDto = objectMapper.readValue(nestedDto);
Set<ConstraintViolation<MyDto>> constraintViolation =
validator.validate(myDto);
if (!constraintViolation.isEmpty()) {
throw new ConstraintViolationException(constraintViolation);
}
}
}
This is pseudo code so i just write it to demonstrate how to solve the problem.这是伪代码,所以我只是写它来演示如何解决问题。 If you want more elegant way, you have to change request because request is wrong here.如果你想要更优雅的方式,你必须改变请求,因为这里的请求是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.