Request Body with optional property
Asked Answered
G

2

10

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.

Goth answered 6/10, 2015 at 13:26 Comment(1)
How do we handle if the request body is a generic, like @RequestBody SearchParam<T> jsonRequest. the flag required=false is applied at SearchParam and not the extending class.Nigercongo
G
21

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) {
Goth answered 6/10, 2015 at 14:39 Comment(0)
T
0

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
   */
}
Tientiena answered 19/9, 2023 at 14:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.