我在spring-boot中创建了一个rest API,问题是我将4个参数作为JSON对象作为requestbody参数。
现在,如果我传递的JSON对象的参数比我的API还要调用的参数多5个,则在序列化JSON对象时不会发生断言异常。 我有一个下面的构造函数的dto类
public class testDto{
@NotNull(message = "fistName can not be null.")
private String fistName;
@NotNull(message = "lastName can not be null.")
private String lastName;
private String nickName;
public testDto() {
}
public testDto(@NotNull(message = "fistName can not be null.") final String fistName ,@NotNull(message = "lastName can not be null.") final String lastName , final String nickName){
super();
this.fistName = fistName;
this.lastName = lastName;
this.nickName = nickName;
}
}
我的restapi ,如下所示,
@PostMapping(path ={ "/api/v1/user"}, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> saveUser(
@Valid @RequestBody(required = true) final testDto dto) throws Exception {
}
现在,在调用我的API时,我传递请求正文,如下所示
{
"fistName" : "abc",
"lastName" : "xyz",
"nickName" : "pqr",
"age" : 25
}
现在在这里,当我传递age
参数并调用API时,我的API仍在工作,而不是引发异常,因为未通过年龄但不是dto类的成员。 >
预期结果:不允许调用API 实际结果:允许我调用API
我也尝试过使用断言异常声明和绑定异常进行,但没有成功。
还设置属性
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
答案 0 :(得分:0)
Spring Boot使用Jackson来将JSON有效负载映射到您的# We use U and A to compute V
U = np.array([[1,2],
[4,3],
[5,6],
[7,8]])
V = np.zeros(U.shape)
A = np.array([[1,3],
[3,4]])
# The for loop to be replaced
for t in range(len(U)):
V[t] = np.argmax( U[t]*A.T ,axis = 1)
类的实例。默认情况下,杰克逊为configured to ignore entries in the JSON that it cannot map to the DTO。这遵循robustness principle或众所周知的Postel定律。
通过将以下行添加到V = np.argmax(U[:,np.newaxis]*A.T,axis=1)
# U[:,np.newaxis]*A.T
中应用程序的testDto
文件中,可以将Jackson配置为无法将JSON中的条目映射到DTO上的属性时失败:
application.properties
答案 1 :(得分:0)
当请求无效json但值正确时该怎么办:
{
"fistName" : "abc",
"lastName" : "xyz",
"nickName" : "pqr",
"nickName" : "pqrs"
}
现在,在这种情况下,它将获取最后一个并映射它