zoukankan      html  css  js  c++  java
  • spring中RequestBody注解接收参数时用JSONField转参数名无效问题

    问题:

      在springboot项目中使用@RequestBody注解接收post请求中body里的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注解无效果。

    解决方案:

      改为使用@JsonProperty(value = "user_name")注解即可,如下:

    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注解无效的情况。

  • 相关阅读:
    Linux shell 学习总结
    linux shell 比较总结
    NSURL基本操作 HA
    Mac node.js install HA
    nodejs学习资料收集 HA
    xcode技巧 HA
    google web app/enxtions 学习资料收集 HA
    Failed to upload *.app on Device 可能的解决方法 HA
    iphone开发常见问题小集2 HA
    cocos2d收集 HA
  • 原文地址:https://www.cnblogs.com/pcheng/p/11550749.html
Copyright © 2011-2022 走看看