Reputation: 1838
I have an endpoint which receives a JSON through POST request.
RequestMapping(value = "/app/login", method = RequestMethod.POST,
headers = { "Content-type=application/json" })
@ResponseBody
public LoginResponse logIn(@RequestBody LoginRequest jsonRequest) {
// code
}
LoginRequest:
public class LoginRequest {
private String user;
private String password;
private String idPush;
private Integer idDevice;
// getters and setters
}
Is there anyway I can specify idDevice as optional?
If I don't send idDevice inside the json, Spring returns a 400 error.
Upvotes: 10
Views: 19949
Reputation: 241
I think that you have a small misconception about java. For resolution of this problem you just have to assign a default value to your optional property like in the example below.
public class LoginRequest {
private String user;
private String password;
private String idPush;
private Integer idDevice = -1;
/*
The change above will make it such that you can exclude that given property from
your JSON. As it now has a default value for cases where you do not assign it
//getters and setters
*/
}
Upvotes: 0
Reputation: 1838
It seems that setting the RequestBody to optional, makes any property optional, not only the full bean.
public LoginResponse logIn(@RequestBody(required=false) LoginRequest jsonRequest) {
Upvotes: 21