search

Home  >  Q&A  >  body text

java - JSONField receives the Json string submitted by the web and parses the key

SpringMVC Controller receives the JSON string submitted by the page POST. Because the JSON string contains all lowercase letters with "_", it is too ugly to write the getters and setters of the properties in Java, so I thought of using JSONField to parse it

//User类
import com.alibaba.fastjson.annotation.JSONField;
public class User{
    @JSONField(name = "user_name")
    private String userName;
    public String getUserName(){
        return this.userName;
    }
    public void setUserName(String userName){
        this.userName=userName;
    }
}

//Controller类
@RequestMapping(value = "/insert_user",method = RequestMethod.POST)
public String insertUser(@RequestBody User user){
    System.out.println(user.getUserName());
    return "ok";
}

But it was not received after the POST was submitted, all were null. Later, using @SerializeName("user_name") still didn't work. Is there any solution to this? Or is my request method wrong? . . .

世界只因有你世界只因有你2769 days ago788

reply all(2)I'll reply

  • 迷茫

    迷茫2017-05-27 17:42:24

    The default json converter of spring mvc is jackson, and you are using @JSONField in fastjson, so it does not work. The next thing you have to do is to replace the default json converter. The specific method is Baidu

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-27 17:42:24

    @RequestBody
    Function:

      i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;
    
      ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
    

    Time to use:

    A) GET and POST methods are used to determine the timing based on the value of the request header Content-Type:

    application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
    multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
    其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

    B) When submitting in PUT mode, judge based on the value of request header Content-Type:

    application/x-www-form-urlencoded, 必须;
    multipart/form-data, 不能处理;
    其他格式, 必须;

    Note: The data encoding format of the body part of the request is specified by the Content-Type of the header part;

    reply
    0
  • Cancelreply