猿问

如何检测所有 json 元素是否用于创建 Java 对象

作为参数,我没有使用 JsonObject,而是使用 MyObject。

@RequestMapping(value = "/api/v1/authenticate", method = RequestMethod.POST)
    public ResponseEntity<TokenDTO> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) {

所以我让 spring 将 json 反序列化为对象,并且我直接使用对象。例子:

authenticationRequest.getUsername();

我正在寻找一些实用程序或注释来检测请求中是否有任何未使用的 json 元素,或者不使用适当的警告处理程序来处理它。


汪汪一只猫
浏览 85回答 1
1回答

慕尼黑5688855

您可以像这样使用@JsonAnySetter:1-定义一个 BaseRequestDTO 类:public abstract class BaseRequestDTO {&nbsp; &nbsp; @JsonAnySetter&nbsp; &nbsp; public Map<String, Object> additionalData=new HashMap<>();}该字段additionalData将保存不在 DTO 中的所有 json 字段2-让你的 d 扩展它,例如:class JwtRequest extends BaseRequestDTO{&nbsp; &nbsp;public String&nbsp; username;&nbsp; &nbsp;public string password;}3-写一个方面来应用你的“严厉”策略:@Aspect@Componentpublic class ControllerArgsValidator {&nbsp; &nbsp; @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")&nbsp; &nbsp; public void restController() {&nbsp; &nbsp; }&nbsp; &nbsp; @Pointcut("within(@org.springframework.stereotype.Controller *)")&nbsp; &nbsp; public void controller() {&nbsp; &nbsp; }&nbsp; &nbsp; @Around("controller() || restController()")&nbsp; &nbsp; public Object validate(ProceedingJoinPoint point) throws Throwable {&nbsp; &nbsp; &nbsp; &nbsp; Object[] args = point.getArgs();&nbsp; &nbsp; &nbsp; &nbsp; for (Object arg : args) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (arg instanceof BaseRequestDTO) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if((BaseRequestDTO) arg).additionalData.isEmpty())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //do what ever;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return point.proceed();&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答