Reputation: 23859
This may be a simple task, but I couldn't find a way to do it. Basically, I need to disallow some parameters at the time of using @RequestBody
annotation in my controller.
Here is my model:
@Data
public class MyModel {
private int id;
private String name;
}
What I want to do is at the time of response, I want both of the properties to be serialized to JSON, but at the time of create or update, I prefer not to receive id
as part of @RequestBody
deserialization.
Right now, if I pass id
in the JSON body, Spring initializes a MyModel
object with its id
set to the passed value.
Reason? The ID cannot be generated until the model is created, so the app shouldn't allow the ID to be set. On update, the ID needs to be passed in the URL itself e.g. (PUT /mymodels/43
). This helps following the REST principles appropriately.
So, is there any way to achieve this functionality?
Update 1:
Right now, I am stuck with using a request wrapper. I created a new class MyModelRequestWrapper
with only name
as its property, and have used it with the @RequestBody
annotation.
Upvotes: 2
Views: 2523
Reputation: 9622
How you do this depends on what version of Jackson you are using. It's basically possible by a combination of the annotations @JsonIgnore and @JsonProperty on relevant fields/getters/setters.
Have a look at the answers here: Only using @JsonIgnore during serialization, but not deserialization
Upvotes: 2