春季请求参数嵌套JSON验证失败。

huangapple go评论73阅读模式
英文:

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(&quot;/s&quot;)
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:
{
&quot;code&quot;: 10004,
&quot;msg&quot;: &quot;参数校验失败&quot;,
&quot;exceptionMsg&quot;: &quot;校验失败:MSG:must not be null, &quot;,
&quot;body&quot;: null

}


However, when I change the &quot;MSG&quot; to lowercase &quot;msg&quot;, 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(&quot;MSG&quot;)
    Message msg;
    int code;
 }

huangapple
  • 本文由 发表于 2020年9月19日 00:38:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63959616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定