Solve the big hole between @ RequestBody and @ Data

  • 2021-11-30 00:22:49
  • OfStack

@ RequestBody with @ Data's pit

If you use @ Data to decorate an entity class, it is best not to use several consecutive identical letters for its attributes, and never use capitalization if you use them.

For example, the following User class


@Data
public class User{
    private Integer userId;
    private String tel;
    private String QQ;
}

If you write this way, the QQ that you get with @ RequestBody in the background method will become null


@PostMapping(value = "/addPrivGroup")
public String addUser(@RequestBody User user){
    return userService.addUser(user);
}

If you must write QQ or qQ, either write getter and setter without @ Data, or add @ JsonProperty to the corresponding attribute (value = "QQ")

The main reason is that when spring accepts parameters, it does not know whether the assignment method is setQQ or setqQ, which leads to the assignment of null

@ requestbody, json, Date type conversion issues

@ requestbody receives json parameter mapping to Date (time and date) type conversion problem in entity class

When app transmits Date type data, there is an 8-hour time difference between app and background reception


@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date departureTime;

timezone mainly solves the "8 hours" problem


Related articles: