英文:
spring request parameter is nested json validation fail
问题
@Controller
public class Test {
@ResponseBody
@PostMapping("/s")
public ResData test(@RequestBody @Valid ResData resData){
System.out.println(resData);
return resData;
}
}
@Data
class ResData{
@NotNull
@Valid
Message MSG;
int code;
}
@Data
class Message {
@NotBlank(message = "s1 cannot be blank.")
String s1;
String s2;
}
但是当我使用类似以下的数据进行测试时:
{
"MSG":{
"s1":" ",
"s2":"ss2"
},
"code":"200"
}
它无法识别,结果如下:
{
"code": 10004,
"msg": "参数校验失败",
"exceptionMsg": "校验失败:MSG:must not be null, ",
"body": null
}
然而,当我将 "MSG" 更改为小写的 "msg" 时,它就可以工作。
但是我的情况需要参数以大写形式传递,有人能告诉我原因吗?
非常感谢!
<details>
<summary>英文:</summary>
[enter image description here][1]I have a request like this:
@Controller
public class Test {
@ResponseBody
@PostMapping("/s")
public ResData test(@RequestBody @Valid ResData resData){
System.out.println(resData);
return resData;
}
}
@Data
class ResData{
@NotNull
@Valid
Message MSG;
int code;
}
@Data
class Message {
@NotBlank(message = "s1 cannot be blank.")
String s1;
String s2;
}
but when I test it with post some data like this:
{
"MSG":{
"s1":" ",
"s2":"ss2"
},
"code":"200"
}
it just cannot recognize:
{
"code": 10004,
"msg": "参数校验失败",
"exceptionMsg": "校验失败:MSG:must not be null, ",
"body": null
}
However, when I change the "MSG" to lowercase "msg", it just worked.
But my situation need the paramter come here is in Uppercase,
could someone tell me the truth?
thank you very much!!
[1]: https://i.stack.imgur.com/hDrmI.png
</details>
# 答案1
**得分**: 2
我建议使用小写的属性命名,但是你可以使用`@JsonProperty`注解告诉Jackson实际的JSON属性是大写的。
```java
@Data
class ResData {
@NotNull
@Valid
@JsonProperty("MSG")
Message msg;
int code;
}
英文:
I would recommend lowercase of property naming, but you can use @JsonProperty
annonation to tell Jackson actual Json property is uppercase
@Data
class ResData{
@NotNull
@Valid
@JsonProperty("MSG")
Message msg;
int code;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论