I'd like to ask you how my rest controller should look like (in springboot) if I want to pass JSON like this
user: {email: "c", password: "c", username: "c"}
btw JSON which looks like this works fine:
{email: "c", password: "c", username: "c"}
so I think that it depends on 'user' word in JSON, but the problem is that my front-end sends all requests like this so better way would be to make this operable in backend.
because one my actual which looks like:
@PostMapping("/users")
public void register(@Valid @RequestBody ApplicationUserEntity newUser){
registerService.registerNewUser(newUser);
}
isn`t acutally working.
Here is the ApplicationUserEntity class:
@Entity
@Data
@Table(name = "users")
public class ApplicationUserEntity implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonIgnore
private Long userId;
@JsonProperty("email")
private String email;
@JsonProperty("username")
private String username;
@JsonProperty("password")
private String password;
public ApplicationUserEntity() {
}
public ApplicationUserEntity(String email, String username, String password) {
this.email = email;
this.username = username;
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"));
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
CodePudding user response:
Your request body can be the following object:
public class Request {
private ApplicationUserEntity user;
// getters, setters ...
}
Its field is the Entity object that you have created. In this case your controller method would look like this:
@PostMapping("/users")
public void register(@Valid @RequestBody Request newUser){
registerService.registerNewUser(newUser);
}
The JSON request in this case would be:
{
user: {
// fields of the ApplicationUserEntity
}
}
Note: It is always recommended that you use DTO objects as requests and response objects. So in this case you would rather have a DTO object that contains the email, username, password field, and put this object as a field in the Request class.