spring中RequestBody注解接收参数时用JSONField转参数名无效问题

问题:spring

  在springboot项目中使用@RequestBody注解接收post请求中body里的json参数的状况。即:json

 1     @RequestMapping(value = "/get-user", method = RequestMethod.POST)
 2     public String getUser(@RequestBody User user) {
 3         System.out.println("user_name:" + user.getUserName());
 4         return JSON.toJSONString(user);
 5     }
 6 
 7 
 8     @Getter
 9     @Setter
10     public class User {
11 
12         private String id;
13 
14         @JSONField(name = "user_name")
15         private String userName;
16     }

  此时,当传递的json参数中,参数名不是userName而是user_name时,会接收不到,至关于使用了@JSONField注解无效果。springboot

 

解决方案:app

  改成使用@JsonProperty(value = "user_name")注解便可,以下:post

1     @Getter
2     @Setter
3     public class User {
4 
5     private String id;
6 
7     @JsonProperty(value = "user_name")
8     private String userName;
9     }

  为何呢?缘由在于@RequestBody注解默认使用的是Jackson来解析的。而@JsonProperty注解才是Jackson的,@JSONField注解则是FastJson的,因此才会致使加@JSONField注解无效的状况。spa

相关文章
相关标签/搜索