如何检测是否使用了所有json元素来创建Java对象
我想在restapi端点()上应用“stern”策略。作为参数,我使用的不是JsonObject,而是MyObject如何检测是否使用了所有json元素来创建Java对象,java,json,rest,spring-boot,deserialization,Java,Json,Rest,Spring Boot,Deserialization,我想在restapi端点()上应用“stern”策略。作为参数,我使用的不是JsonObject,而是MyObject @RequestMapping(value = "/api/v1/authenticate", method = RequestMethod.POST) public ResponseEntity<TokenDTO> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest
@RequestMapping(value = "/api/v1/authenticate", method = RequestMethod.POST)
public ResponseEntity<TokenDTO> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) {
我正在寻找一些UTIL或注释来检测请求中是否有任何未使用的json元素,或者不使用适当的警告处理程序来处理它。您可以像这样使用@JsonAnySetter: 1-定义BaseRequestDTO类:
public abstract class BaseRequestDTO {
@JsonAnySetter
public Map<String, Object> additionalData=new HashMap<>();
}
3-写一个方面来应用你的“严厉”策略:
@Aspect
@Component
public class ControllerArgsValidator {
@Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
public void restController() {
}
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controller() {
}
@Around("controller() || restController()")
public Object validate(ProceedingJoinPoint point) throws Throwable {
Object[] args = point.getArgs();
for (Object arg : args) {
if (arg instanceof BaseRequestDTO) {
if((BaseRequestDTO) arg).additionalData.isEmpty())
//do what ever;
}
}
return point.proceed();
}
作为一个选项,您可以将自定义
ObjectMapper
定义为Bean
,并在json中遇到unknown
或missing
属性时使其失败<代码>新建ObjectMapper().configure(缺少创建者属性的反序列化功能.FAIL_,Boolean.TRUE)。configure(未知属性的反序列化功能.FAIL_,Boolean.TRUE)您能否澄清一下,作为验证的输出,您希望得到什么?400状态码?只需记录一条警告语句?实际上,只需记录或发送一些验证信息到frontendfor我就足以看到@JsonAnySetter注释,但知道如何预处理控制器还是很好的
class JwtRequest extends BaseRequestDTO{
public String username;
public string password;
}
@Aspect
@Component
public class ControllerArgsValidator {
@Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
public void restController() {
}
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controller() {
}
@Around("controller() || restController()")
public Object validate(ProceedingJoinPoint point) throws Throwable {
Object[] args = point.getArgs();
for (Object arg : args) {
if (arg instanceof BaseRequestDTO) {
if((BaseRequestDTO) arg).additionalData.isEmpty())
//do what ever;
}
}
return point.proceed();
}